Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use typeof in generic class

Tags:

c#

generics

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>>();
like image 537
Morteza Nemati Avatar asked Jul 28 '13 09:07

Morteza Nemati


People also ask

Can dynamic type be used for generic?

You can make use of generics, so you can pass in the dynamic type for the serializer.

What is generic type class?

A generic type is a class or interface that is parameterized over types. We use angle brackets (<>) to specify the type parameter.

What is a generic type parameter?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

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

like image 165
Sriram Sakthivel Avatar answered Nov 14 '22 21:11

Sriram Sakthivel