How to create dynamic list type in C#?

Hello, I would like to create a helper function in the class, which can be used by multiple List types at the same, so how can I create initialize or create function to pass List<T> where T can be any type of class in C#?

Asked by:- pika
: 230 At:- 8/28/2019 1:20:08 PM
C# dynamic list type

1 Answers
profileImage Answered by:- vikas_jk

You would have to create dynamic list type using Reflections.

string something = "Some String";
Type type = something.GetType(); //get type
Type listType = typeof(List<>).MakeGenericType(new [] { type } );
IList list = (IList)Activator.CreateInstance(listType);

The above method is useful when you want to create list of unknown type.

At:- 9/18/2019 8:28:38 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly