Generics - T constructor
A couple of days ago I found an irritating limitation in .Net 2.0 Generics.
Lets say I want to create some sort of a generic object factory, I'll define the following interface:
namespace Sternr.Tests
{
public interface IGenericFactory
{
public T CreateInstance<T>();
}
}
Where T is the type of object I want to create.
In .Net 1.x, if I wanted to create a new instance of a specified Type, I needed to use reflection, but in 2.0 you can use the following manner:
T newInstance = new T();
Which is prettier ;)
All you need to do to use this syntax, is declare that T has a default constructor:
public T CreateInstance<T>() where T: new()
For now, everythink looks good, but what happens if I want to make my factory smarter - and I want to support a parameterized constructs?
One would think the following should do the trick:
public T CreateInstance<T>() where T: new(object[] args)
But it turns out this syntax is NOT supported and will result in compilation error!
In order to overcome this limitation I had use my last resort - reflection...
Oh well, lets hope it's been fixed in 3.0...
2 comments:
You can use Activator.CreateInstance&stT>
Hey Chaim!
Look in this post for more info:
http://iblogable.blogspot.com/2007/03/t-from-type-generics-2.html
Post a Comment