What is the purpose of typeof in C#?
In C#, the typeof operator is used to obtain the Type object for a specified type. It returns an instance of Type that represents the specified type and can be used to access metadata information about the type, such as type name, base class, interfaces, members, etc.
The syntax for typeof is as follows: typeof(type)
For example, if you need to obtain a Type object of the string type, you can use the typeof operator:
Type type = typeof(string);
Then, you can use the Type object to access information about the type, for example:
Console.WriteLine(type.Name); // Outputs: “String”
Console.WriteLine(type.BaseType); // Outputs: “System.Object”
The typeof operator is commonly used in reflective programming to dynamically retrieve and manipulate information about types. It is also very useful when writing generic code and calling generic methods.