HI, I have a requirement to create instance for list object at runtime using reflection. For example I have 2 classes like below,
class Class1
{
List<Class2> class2List;
public List<Class2> Class2List
{
get;set;
}
}
class Class2
{
public string mem1;
public string mem2;
}
After creating the instance of Class1
at Runtime in another class Class3
, I want to assign values to all the properties of the class. In this case, Class2List
is a property of List<Class2>
. At Runtime, I don't know the class type of List<Class2>
. How can I initialize the property i.e. List<Class2>
inside class3 at runtime.
Any suggestions are greatly appreciated...
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. Collections. Generic namespace.
AddRange(), List. Insert(), and List. InsertRange() methods are used to add and insert items to a List<T>. List<T> is a generic class.
In C# you can simply return List<string> , but you may want to return IEnumerable<string> instead as it allows for lazy evaluation.
Rather than question your motives or try to unpick what you're doing - I'm just going to answer the question in the title.
Given you have a type instance listElemType
that represents the type argument that is to be passed to the List<>
type at runtime:
var listInstance = (IList)typeof(List<>)
.MakeGenericType(listElemType)
.GetConstructor(Type.EmptyTypes)
.Invoke(null);
And then you can work with the list through it's IList
interface implementation.
Or, indeed, you can stop at the MakeGenericType
call and use the type it generates in a call to Activator.CreateInstance
- as in Daniel Hilgarth's answer.
Then, given a target
object whose property you want to set:
object target; //the object whose property you want to set
target.GetType()
.GetProperty("name_of_property") //- Assuming property is public
.SetValue(target, listInstance, null); //- Assuming .CanWrite == true
// on PropertyInfo
If you don't know the properties of the type represented by target
, then you need to use
target.GetType().GetProperties();
to get all the public properties of that instance. However just being able to create a list instance isn't really going to be able to help you there - you'll have to have a more generic solution that can cope with any type. Unless you're going to be specifically targetting list types.
Sounds to me like you might need a common interface or base...
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