General list using reflection

I have a script where I got Class name as a string I just want to create a general List this class. I tried the following

  Type _type = Type.GetType(className); List<_type> list = new List<_type>(); 

But I get error . I cannot specify this _type as a list argument. If anyone knows please help me

+4
source share
4 answers

Closest you can get:

 Type listType = typeof(List<>).MakeGenericType(_type); IList list = (IList) Activator.CreateInstance(listType); 
+10
source

Reflection occurs at run time, since the type of the object can be changed to something using the running program.

Type parameters (generics), on the other hand, are used only by the compiler to check type safety.

Thus, it is not possible to use reflection indicating a type parameter because the compiler does not know anything about the result of reflection.

+2
source

If you are using .Net 4, then using dynamic may help. In this case, you can use methods in the instance that are not accessible through non-common interfaces (for example, IList ).

For example, using dynamic allows you to call the AddRanges method of a list, which you could not do using IList translation:

 Type _type = typeof(int); Type listType = typeof(List<>).MakeGenericType(_type); dynamic list = Activator.CreateInstance(listType); list.Add(1); list.AddRange(new int[] {0, 1, 2, 3}); 

However, this method is not as similar to a type as pointing to a non-generic interface, because it cannot catch errors at compile time.

+1
source

Unfortunately, this is not possible, since the generators must be known at compile time. You are trying to override this by making them known at run time. The reason they should be known at compile time is because the compiler can verify that all variables passed to it are valid. AFAIK, doing what you want will require a complete census of generics.

The main reason for checking compilation time is that _type can change at runtime, and then there will be overhead when adding to List<T> , since the JIT compiler will have to do type checking.

What @MarkusJarderot says is the closest you can get as interfaces are used instead of generics.

0
source

All Articles