Opposite of typeof /GetType()

A

Ade

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.
 
M

Marc Gravell

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
 
J

Jon Skeet [C# MVP]

Ade said:
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.

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.
 
P

pipo

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();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top