Whereas typeof gets a Type from a class, I need to get a class from a
Type so that I may create the type at runtime.
Imagine if you wil
class foo
{
public foo bar()
{
foo newFoo = new GetType();
// Some magic goes here
return newFoo;
}
}
What would be the syntactically-correct way to do this? I want to
create, from the base class, a new instance of whatever type the
instance of foo is. eg calling bar() on
class superfoo : foo
will give me something unboxable to a superfoo.
Marc Gravell - 10 Mar 2008 14:12 GMT
I'm assuming that this is an extension of the ArrayList converstaion,
so generics etc are out of the question...
How about:
foo newFoo = (foo) Activator.CreateInstance(GetType())?
Another option is a virtual method for creating a new instanc, but
this has a maintenance cost (i.e. you need to remember to override
it). But might be an option if you can't guarantee a default ctor.
Alternatively - I already posted an example that used
MemberwiseClone() to do this, changing the single property afterwards.
Since this is essentially a blit, it should out-perform any reflection-
based implementations.
Marc
Jon Skeet [C# MVP] - 10 Mar 2008 14:13 GMT
> Whereas typeof gets a Type from a class I need to get a class from a
> Type so that I may create the type at runtime.
[quoted text clipped - 18 lines]
>
> will give me something unboxable to a superfoo.
Well, I don't think boxing/unboxing actually comes into it, but I
suspect what you're after is:
Activator.CreateInstance(GetType());
Note that it will only work if there's a parameterless constructor - if
you don't have a parameterless constructor, you'll need to specify
constructor parameters too.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
pipo - 10 Mar 2008 17:03 GMT
Sorry, if I misunderstood your question.
public class Foo<T>
where T : new()
{
protected T bar()
{
return new T();
}
}
public class SuperFoo : Foo<SuperFoo>
{
//Class code
}
SuperFoo super = new Foo<SuperFoo>().bar();
> Whereas typeof gets a Type from a class, I need to get a class from a
> Type so that I may create the type at runtime.
[quoted text clipped - 18 lines]
>
> will give me something unboxable to a superfoo.