typeof and Unbound Generic Types - CSharp Custom Type

CSharp examples for Custom Type:Generics

Introduction

Open generic types do not exist at runtime, since they are closed as part of compilation.

The only way to specify an unbound generic type in C# is with the typeof operator:

class A<T> {}
class A<T1,T2> {}


Type a1 = typeof (A<>);   // Unbound type (notice no type arguments).
Type a2 = typeof (A<,>);  // Use commas to indicate multiple type args.

Open generic types are used in conjunction with the Reflection API.

You can also use the typeof operator to specify a closed type:

Type a3 = typeof (A<int,int>);

or an open type:

class B<T> { void X() { Type t = typeof (T); } }

Related Tutorials