Home > C# > C# – Generics – What is typeof(T) ?

C# – Generics – What is typeof(T) ?

Answer:
typeof(T).ToString() shows name of the passed class type, however,
typeof(T) is System.RuntimeType.

This is another caveat of C# generics.

For example. Suppose you invoke this method:

    Form frm = _factoryView.CreateForm<Form>();

And the CreateForm method has following signature

    public T CreateForm<T>() where T : Form, new()

You may think this line gives you a true statement. It is not.
This line will always give a false result.

    if (typeof(T) is System.Windows.Forms.Form)

Here is complete snippet of the method.

public T CreateForm<T>() where T : Form, new()

{

    if (typeof(T) is System.Windows.Forms.Form)

        //this will always be FALSE

    T frm = new T();

    if (frm is System.Windows.Forms.Form)

        //this will be checked

}

And here is what Immediate Window shows us:

?typeof(T).ToString()
"System.Windows.Forms.Form"
?typeof(T) is System.Windows.Forms.Form
false
?typeof(T) == System.Windows.Forms.Form
'System.Windows.Forms.Form' is a 'type', which is not valid in the given context
?typeof(T) is System.RuntimeType
true
?frm is System.Windows.Forms.Form
true

Moral of the story, only apply is operator on instantiated object, never on typeof(T).

Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment