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?
You can do it using a lambda:
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.