Hi,
Einar Værnes schrieb:
> Hi.
> I am trying to programatically decide which type a new object should have,
> but the typeof-function is apparently not the answer, as the following code
> will not compile.
>
> class AbstractClass:Object { }
>
> class DerivedClass1 : AbstractClass { }
>
> class DerivedClass2 : AbstractClass { }
>
> static class Program
> {
> static void Main()
> {
> AbstractClass a,b,c;
> a = new DerivedClass1();
> b = new DerivedClass2();
> if (some_condition)
> c = new (typeof(a))();
> else
> c = new (typeof(b))();
> }
> }
>
> How can implement this?
Take a look into the System.Reflection namespace. With typeof you will
get a Type object. The Assembly type has a CreateInstance method, which
will create a new object of a type:
AbstractClass myObject;
// ...
Type t = typeof(myObject);
Assembly a = Assembly.GetAssembly(t);
AbstractClass newObject = a.CreateInstance(t.FullName);
// ...
There are several signatures for Assembly::CreateInstance. So you can
pass arguments to the constructor, for example.
Btw and not concering your question, I find it confusing to have a class
that is named "AbstractClass" but is not declared abstract. But that
just a metter of "taste"
HTH,
Tobi