Something I've been thinking about from time to time: Why is the typeof operator needed in C#? Doesn't the compiler know that public class Animal
is a type just by the very definition? Why do I need to specify SomeMethod(typeof(Animal))
when I need to reference a type?
The typeof operator is used to get the data type (returns a string) of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type.
The typeof is an operator keyword which is used to get a type at the compile-time. Or in other words, this operator is used to get the System. Type object for a type. This operator takes the Type itself as an argument and returns the marked type of the argument.
The C# typeof operator ( GetType operator in Visual Basic) is used to get a Type object representing String. From this Type object, the GetMethod method is used to get a MethodInfo representing the String. Substring overload that takes a starting location and a length.
Animal
is simply the name of the type, typeof(Animal
) returns the actual type object (System.Type
instance). Sure, it may have been possibly just to have the type name returning the type object in code, but it makes the job a lot harder for the compiler/parser (recognising when a type name means typeof or something else) - hence the existence of the typeof
keyword. It also arguably makes the code clearer to read.
typeof(Class)
is the only way to express Type as a literal. When you write Class.SomeField
you mean static field. When you write typeof(Class).SomeField
you reference field of object of class Type
that represents your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With