0

Am i trying to achieve the impossible or is it simply unnecessary? The code in GetList is the same for all specializations of the class A, apart from the bit to create a new instance of the specialization. There is no default constructor, always the same list of parameters.

At the moment I am using instead public static List<A> GetList(int i, Func<A> createMeAnInstance)

Which feels unclean.

abstract class A
{
  protected A (int i)
  {

  }

  public static List<T> GetList<T>(int i) where T : A
  {
    var list = new List<T>();
    for(int x = 1; x< 100; x++)
    {
     var o = new T(i);
     list.Add(o);
    }
  }
 }   

 public class B : A
 {
    public B (int i) : base(i) {}
 }

 ...

 var list = A.GetList<B>(1);
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155

5 Answers5

3

Operator new compiles as call Activator.CreateInstance.

Just write

Activator.CreateInstance(typeof(T), new object[] {i})

not perfect but works.

gandjustas
  • 1,925
  • 14
  • 12
  • 1
    No, it doesn't compile as a call to `Activator.CreateInstance` – Dyppl Apr 11 '11 at 14:57
  • http://stackoverflow.com/questions/367577/why-does-the-c-compiler-emit-activator-createinstance-when-calling-new-in-with-a – gandjustas Apr 11 '11 at 15:02
  • I'm tempted to mark this one as correct. Seems the cleanest to me. Sending in a instantiating code as a parameter doesnt seem DRY to me. Any comments as to Func param vs Activator.CreateInstance ? – jenson-button-event Apr 11 '11 at 15:03
  • Activator.CreateInstance is slow, but with Func you actually specifies creation of object outside of your function. It's an arbitary decision depending on your problem. – gandjustas Apr 11 '11 at 15:06
  • @gandjustas: ok, you were right and I apologize. Thanks for the link, it was new for me – Dyppl Apr 11 '11 at 15:07
  • I've marked this up as its an option and not incorrect, but I've chosen the delegate approach - it might not be dry but Its safer IMO. – jenson-button-event Apr 11 '11 at 15:15
2

You can't call parameterized constructors on generic types. Your Func<> version is the best approach here.

Sean
  • 60,939
  • 11
  • 97
  • 136
0

You can't do that. You only can specify new() as a type constraint for constructors.

Why don't you take the B instance directly in GetList?

List<B> list = A.GetList(new B(i));

Use this code:

public static List<T> GetList<T>(T o) where T : A
{
    var list = new List<T>();
    list.Add(o);
    return list;
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

If I understand you correctly... You can create an instance of T by reflecting it's constructors, or using the Activator.

M.A. Hanin
  • 8,044
  • 33
  • 51
0

I think it's better to use default constructor and move i to the base class (A) as a field. But in some situations it could be more appropriate to use reflection

Archeg
  • 8,364
  • 7
  • 43
  • 90