6

I Create Generic class like this:

public class Sample<T> where T : class
{
    public DoSomething();
}

then I create new class :

public class Sample2
{
    Sample<Sample2> obj=new Sample<Sample2>();
}

why can't i use the below code to create an instance of Sample class in Sample2 class?

        Sample<typeof<this>> obj=new Sample<typeof<this>>();
haim770
  • 48,394
  • 7
  • 105
  • 133
Morteza Nemati
  • 237
  • 3
  • 9
  • Possible duplicate of http://stackoverflow.com/questions/2107845/generics-in-c-using-type-of-a-variable-as-parameter – haim770 Jul 28 '13 at 09:15
  • 1
    Mainly because generics are evaluated at compile-time. The `typeof` function returns a Type class at runtime. You could use Activator.CreateInstance instead: http://msdn.microsoft.com/en-us/library/wccyzw83.aspx – CodingIntrigue Jul 28 '13 at 09:17
  • 2
    Additionally, I don't think you can reference `this` in a field initializer, since the object has not been constructed at that point – HugoRune Jul 28 '13 at 09:19
  • 2
    Because: 1. `typeof` is not generic. It's `typeof(...)`. 2. `typeof` takes a type literal (or parameter), not a reference. 3. Generics and `Type`s do no mix (not without reflection): either use strong-type generics, or reflection and `Type`/`typeof`. – Kobi Jul 28 '13 at 09:19

1 Answers1

7

Answer is simple Generics need to be Compile time but what you're doing is obviously not known during Compile time

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 1
    I'm not sure what you mean. First, generics is also a .Net run time feature, not just a C# compile time feature. Second, certainly the type of the current class is known at compile time? If anything, you would not know the type of `T` inside `Sample` (terrible name), but this is not the case. – Kobi Jul 28 '13 at 09:26
  • Makes sense, but not completely true. Read this answer to see how to do it: http://stackoverflow.com/a/687420/72350 – Diego Jancic Aug 11 '15 at 18:41
  • @Diego thanks for the comment. I'm aware of the reflection approach but in general reflection should be avoided unless it's really really needed. – Sriram Sakthivel Aug 11 '15 at 18:55