Illustration of Operator Keyword typeof with Examples in C# (C Sharp) In this
article, you will understand about how to determine the type of a value
type or any open generic types using typeof operator keyword of C#. The
article doesnt stop with that; it also suggests an alternative solution
to typeof operator which helps you in determining the type of an expression
during runtime.
As stated above, typeof operator is used to determine the type and returns the corresponding System.Type object associated with this type. To start with, here is a simple example illustrating the usage of this operator: class sampleClass
{ Output of
this code will be: Note that the types determined by typeof belong to either System namespace or to the System.IO namespace. Usage of typeof operator has few limitations which are listed below: It
can never be overloaded In the above example, you have displayed the type of value types directly. What if you have to store the type in a variable and use it at a later point of time? For that, you can store the result in a type variable. The above example can be modified to store the types as shown below: class sampleClass
{ Output of this code will be same as that of the earlier example. You might wonder why to store the result in a type variable. This is because if you want to perform the same type operation multiple times, that will be a performance hit. Instead you can record it in a type variable once and directly use the type variable wherever appropriate. Declaring the type variable as static is yet another way of improvising the performance. In the examples discussed so far, typeof operator is used to determine value types. Other than that, you can also determine the type of open generic types like class using this operator. Here is a corresponding code sample: class sampleClass
{ If you store the type information of a class in a type variable, you can retrieve more information about the class using System.Reflection and the corresponding methods. The Main() method of the example mentioned above can be modified as shown below to use few such methods of System.Reflection: public static
void Main() { Output of
this code will be: Methods of
sampleClass are: Members (including
methods) of sampleClass are: So far, you have determined the type of a pre-determined type be it a value type or a class. What if you have to determine the type of an expression during runtime? You can do it using the GetType() method shown in the above output. Here is an example: class sampleClass
{ Output of
this code will be: Not very specific to run time expressions, you can use GetType() method as an alternative to typeof operator as well. Consider the following piece of code: sampleClass
obj = new sampleClass(); Irrespective of which approach you use, you can apply any of the earlier discussed methods of System.Reflection to fetch additional information about the type variable.
|