tags:

views:

230

answers:

2

Hello! I'd like to write a generic method that creates a new instances of a specified Type. I tried

protected T CreateNew<T>()
    where T : new()
{
    return new T();
}

This works, but only if I specified the type at compile time, just like

var x = CreateNew<Point>();

The point is, that I need to do something like this

ISomeInterface inter;
if (selection == 1)
    inter = new SomeClass();
else
    inter = new SomeClass2();
// ...
ISomeInterface inter2 = CreateNew<typeof(inter)>();

where SomeClass implements ISomeInterface. But this fails to compile as CreateNew() needs an actual type specified. I don't know if it's possible to provide something like that at runtime, but the above code fails to compile.

So I have an instance of an unknown reference type and I need to create several instances of the same type.

Does anyone know a technique to achive this behaviour?

+10  A: 

The point of generics is to provide a mechanism whereby code can be reused for different types when the type is known at compile-time. In this case, you don't know the type at compile-time.

I suggest you use Activator.CreateInstance(inter.GetType());

Jon Skeet
Thanks a lot!I was just confused about generic methods, as I guess I did not correctly understand something about generics written in C# in a nutsheel that stated generics can be reused at runtime (unlike C++ templates)
Yes, generic types in .NET *are* reused at execution time (i.e. the code is only defined once) but the type has to be *chosen* at compile-time (leaving aside reflection).
Jon Skeet
+1  A: 

You can do it using a lambda:

Function<ISomeInterface> creationDelegate;
if (selection == 1)
    creationDelegate = () => CreateNew<SomeClass>;
else
    creationDelegate = () => CreateNew<SomeClass2>;
ISomeInterface inter = creationDelegate();

// ...
ISomeInterface inter2 = creationDelegate();

I can't see the benefit of using the CreateNew method in this case based on your example code, but I'm assuming that your "real" code is more sophisticated.

Michael Meadows