0
votes

I have a base class (Baseclass) from which I derived some subclasses (Subclass1, Subclass2, etc.). For each subclass, I want:

  • call the constructor with 'fixed' arguments (arg1, arg2, etc.);
  • check if the instantiation is valid (supposing to have a common method IsValid); and
  • add the instantiation to a list of object.

Here follows the excerpt of the code:

subclassList = new List<Type>()
{
   typeof(Subclass1),
   typeof(Subclass1),
   ...
};
List<Baseclass> objectList = new List<Baseclass>();
foreach (Type subclass in subclassList)
{
   ConstructorInfo[] constructorArray = subclass.GetConstructors(BindingFlags.Public);
   object o = constructorArray[0].Invoke(new object[] { arg1, arg2, ... });
   if (((Baseclass)o).IsValid)
   {
      objectList.Add(Convert.ChangeType(o, subclass));
   }
}
2
What is the problem? - Roman Doskoch

2 Answers

0
votes

You are trying to add an item of type object into your objectList. You should cast the converted item to Baseclass for the Add method to accept to pass the compilation:

                var conv = Convert.ChangeType(o, subclass);
                objectList.Add((Baseclass)conv);
0
votes

Convert.ChangeType is not really needed in this case, you would just need one cast. Also, if you need to invoke a constructor, you can use the Activator class, which is more convenient for this case than using reflection.

Here is a complete working example:

using System;
using System.Collections.Generic;

// some fake classes just so I can compile the example
class Baseclass {
    public bool IsValid {
        get { return true; }
    }
}
class Subclass1 : Baseclass {
}
class Subclass2 : Baseclass {
}

class Program {

    static void Main(string[] args) {

        var subclassList = new List<Type>() {
           typeof(Subclass1),
           typeof(Subclass1)
        };
        List<Baseclass> objectList = new List<Baseclass>();
        foreach (Type subclass in subclassList) {
            Baseclass newObject = (Baseclass)Activator.CreateInstance(subclass);
            if (newObject.IsValid) {
                objectList.Add(newObject);
            }
        }

    }
}