I have a factory that needs to create objects that inherit from the Foo class at runtime. I think the return type of System.Activator.CreateInstance was the same as the type of the object being created, but judging by the following error message, its return type is Object.
Error 1: It is not possible to implicitly convert the type 'object' to 'cs_sandbox.Foo'. Explicit conversion exists (are you skipping listing?) F: \ projects \ cs_sandbox \ Form1.cs 46 24 cs_sandbox
Ok, maybe I miss the role, but
return (t)System.Activator.CreateInstance(t);
leads to another error message, which, I must admit, makes no sense to me:
Error 1: Could not find the name of the type or namespace 't' (do you miss the using directive or assembly references?) F: \ projects \ cs_sandbox \ Form1.cs 45 25 cs_sandbox
And here is my code:
class Foo { }
class FooChild1 : Foo { }
class FooChild2 : Foo { }
class MyFactory
{
public static Foo CreateInstance(string s)
{
Type t;
if (s.StartsWith("abcdef"))
{
t = typeof(FooChild1);
return System.Activator.CreateInstance(t);
}
else
{
t = typeof(FooChild2);
return System.Activator.CreateInstance(t);
}
}
}
How can I fix this code? Or, if it is not fixed, what are the other ways to create objects that inherit from a particular class at runtime?
source
share