Sunday, March 23, 2014

typeof

typeof is an operator, which cannot be overloaded.
Used to obtain the System.Type object for a type.
This operator uses reflection to access the metadata descriptions of the types.
There is only one System.Type object for any given type. This means that for a type T, typeof(T)==typeof(T) is always true. This type cannot be dynamic.

Synatx: typeof(type)
             typeof(unbound-type-name)
             typeof(void)

It returns the System.Type object for the specified type.

[Note: An Unbound-type-name is very similar to a type name except that an unbound-type-name contains generic-dimension-specifiers wherea type-name contains type-argument-lists.]

Examples:
typeof(int);  //System.Int32
typeof(List<int>);  //System.Collections,Generic.List'1[System.Int32]
typefo(Dictionary<,>);  //System.Collections,Generic.Dictionary'2[TKey,TValue]
typeof(void); //System.Void

   The result of typeof(void) is the System.Type object that represents the absence of a type. This special type object is useful in class libraries that allow reflection onto methods in the language, where those methods wish to have a way to represent the return type of any method, including void methods, with an instance of System.Type.

Test:
Employee objEmployee = new Employee();
System.Type t = typeof(objEmployee); //throws error, because typeof only works on types, not on variables.
System.Type t = typeof(Employee) ; //it is fine.

No comments:

Post a Comment