Im trying to accomplish something which may seem a bit convoluted but would be quite helpful in my situation, looks something like this.
public class CommonBaseClass {}
public class Type1Object : CommonBaseClass {}
public class Type2Object : CommonBaseClass {}
public class Type3Object : CommonBaseClass {}
public static Dictionary<string, Type> DataTypes = new Dictionary<string, Type>()
{
{ "type1" , typeof(Type1Object) },
{ "type2" , typeof(Type2Object) },
{ "type3" , typeof(Type3Object) }
};
public static CommonBaseClass GetGenericObject(string type)
{
return new DataTypes[type](); //How to instantiate generic class?
}
Because I can guarantee that all the constructors have the same signature I know this will work, just not sure how to let the compiler know.
Thanks in advance
I don’t see any generics in here really, but it looks like you want:
If you need to use parameterized constructors, use an alternative overload of
Activator.CreateInstance.Alternatively, consider changing your dictionary to be of delegates: