I was wondering if it possible to instantiate a parameterized Generic eg
public T GetListViewData
{
return new T(this.OrganizationalUnitId, DateTime.Now));
}
first I tried it having the AbstractOrganizationalUnit-class abstract. Then I modified it to public. AbstractOrganizationalUnit has a constructor which actually takes this signature and so do all child classes of AbstractOrganizationalUnit.
Any idea how to approach that???
thanks in advance antoschka
Sunny ChenPosted Jul 2, 2008, 5:46 AM
Yes it is possible, but firstly you should remove the new() constraint on the method signature.
1. Create the abstract class.
public abstract class AbstractOU
{
public AbstractOU(int id, DateTime dt)
{
}
}
2. Create the derived class:
public class OU : AbstractOU
{
public OU (int a, DateTime b) : base(a,b){}
}
3. Create your method which looks like this:
private T GetOU() where T:AbstractOU
{
//return new T(100, DateTime.Now);
//Type type = Type.GetType(T);
T ret = (T) Activator.CreateInstance(typeof(T), new object[] { 100, DateTime.Now });
return ret;
}
If you add the new() constraint on the method signature above, the c# compiler would require a parameterized default constructor on the class definition when you call the method by :
AbstractOU a = GetOU();
Hope this helps!