What does Typeof Operator mean?
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.
Techopedia explains Typeof Operator
The Typeof operator can be used with any one of the following parameters:
- A type that is not dynamic
- An unbound type name representing a generic type with list of arguments. These are specified with appropriate commas.
- the keyword "void"
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.
The GetType method is an alternative option to the typeof() operator. It can be used to fetch the type of an expression during runtime, in addition to static and predetermined types.
Survey: Why Is There Still a Gender Gap in Tech?
Do you work in the tech industry? Help us learn more about why
the gender gap still exists in tech by taking this quick survey!
Survey respondents will also be entered to win a $100 Amazon Gift Card!