Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
Typeof operator, in C#, is an operator used to determine the type of the parameter passed to it. It returns the System.Type object associated with that type, which holds all the details related to the given type.
The feature of reflection in the .NET framework is a powerful mechanism by which the capabilities of a type can be known and used at run time. The typeof operator uses the capabilities of reflection to query the information related to both value and reference types such as constructors, events, fields, properties, module and assembly in which the type is deployed.
The typeof operator can be used as a part of an expression to obtain the reference of the Type object for various types that are used in the compilation unit. It can be used to display the Type references as strings and can also be assigned to a variable of type, System.Type or a field. It is used in Enum static methods, DataTable class and the conversion methods of ArrayList.
For example, a typeof operator can be used with StreamReader , a type defined in the .NET framework library to store it in a variable of System.Type. This type variable can then be used to query for details such as the class type (abstract or concrete), methods, etc.
The typeof operator can be used to determine the public types defined in System.IO or System namespace. It cannot be overloaded with custom implementation.
As the typeof operator uses the reflection technique to access the metadata description of the type, it makes it slow when used for optimized code and hence should be used less frequently. Storing the return type of a typeof operator in a static variable can improve performance in some cases.