Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

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?

like image 717
user3381672 Avatar asked Mar 09 '14 23:03

user3381672


People also ask

How do you create a list variable type?

Select a list Type. To create a list of a simple type, select one of the types shown. To create a list of a complex type, from Type select Complex Variable and from Complex Variable Type select the complex type, for example, Timer.

What is list t?

The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.

What type of list is C# list?

C# List. List is a strongly typed list of objects that can be accessed by index. It can be found under System. Collections.


1 Answers

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();
like image 140
Lee Avatar answered Sep 20 '22 14:09

Lee