Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is typeof needed?

Tags:

c#

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?

like image 496
ciscoheat Avatar asked Jun 30 '10 13:06

ciscoheat


People also ask

What is the use of typeof ()?

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.

Why do we use typeof in C#?

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.

What is typeof C#?

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.


2 Answers

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.

like image 74
Noldorin Avatar answered Sep 20 '22 00:09

Noldorin


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.

like image 21
Andrey Avatar answered Sep 22 '22 00:09

Andrey