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?
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.
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.
C# List. List is a strongly typed list of objects that can be accessed by index. It can be found under System. Collections.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With