Search code examples
.netobjectsystem.reflection

How can I instantiate a property of a class by knowing just the type


I have a class that contains several other classes as properties. Initially, none of the properties are instantiated. I would like to instantiate a single property by passing the property itself in the Load function.

public class MyMainClass
{
    public ClassA A { get; set; }
    public ClassB B { get; set; }
    public ClassC C { get; set; }
    // ...
    // ...
    // Many more. All these classes are inherited from Class0

    public void Load(Class0 UnknownClass)
    {
        if ((UnknownClass) is ClassA) A = new ClassA();    
        if ((UnknownClass) is ClassB) B = new ClassB();    
        if ((UnknownClass) is ClassC) C = new ClassC();
        //  and so on... This should to be done in a loop 
    }
}

public void Main()
{
    MyMainClass MyObj = new MyMainClass();
    MyObj.Load(MyObj.ClassA);  // This should instantiate MyObj.ClassA
    MyObj.ClassA.SomeMethod();
}

Class0 is the base class for ClassA, ClassB and so on.

This works fine. But I do not want to write a whole bunch of comparisons for each class. I need to loop through the properties, find a matching type and instantiate it. I probably need to use system.reflection, but not sure how...

There are other similar answers, but each instantiate a new object based on the Type passed. I need to instantiate the property of the class.


Solution

  • Okay, I finally figured it out after combining several other answers:

    public void Load<T>() where T : new()
    {
        object lObj = Activator.CreateInstance(typeof(T));  // instantiate a new object of type passed
    
        // Loop through properties and assign object to the property that matches its type
        System.Reflection.PropertyInfo[] lProps = typeof(MyMainClass).GetProperties();
        foreach (System.Reflection.PropertyInfo lProp in lProps)
        {
            if ((typeof(T).ToString() == lProp.PropertyType.Name)) lProp.SetValue(this, lObj);
        }
    }