user3381672
user3381672

Reputation: 1512

How do I create List<type> for runtime type?

I have some code like this, I don't know what type is until runtime.

Type type;

And I need a list defined as:

List<type>

I've tried

var listType = typeof(List<>).MakeGenericType(new []{type});

IList list = Activator.CreateInstance(listType));

But it does not work well because I need to pass this list to XmlSerializer.Serialize method. It only output a correct result when this list is defined exactly List

for example: When I pass in

List<String> list = new List<String>()

It output

<ArrayOfString>...</ArrayOfString>

When I pass in

IList list = new List<String>()

It will output

<ArrayOfAnyType>...</ArrayOfAnyType>

which is not what I want.

How can I define a List when I don't know what type is at compile time?

Upvotes: 6

Views: 1789

Answers (1)

Lee
Lee

Reputation: 144136

I assume you're creating the serialiser with:

var serialiser = new XmlSerializer(typeof(IList));

you should pass the real list type:

var serialiser = new XmlSerializer(list.GetType());

Note the following works as expected:

var t = typeof(List<>).MakeGenericType(typeof(string));
var list = (System.Collections.IList)Activator.CreateInstance(t);
list.Add("string1");
list.Add("string2");

var serialiser = new System.Xml.Serialization.XmlSerializer(list.GetType());
var writer = new System.IO.StringWriter();
serialiser.Serialize(writer, list);

var result = writer.GetStringBuilder().ToString();

Upvotes: 5

Related Questions