Why is tipof needed?

Something I thought about from time to time: why do I need a typeof operator in C #? Doesn't the compiler know that the public class Animal is a type by definition only? Why do I need to specify SomeMethod(typeof(Animal)) when I need to refer to a type?

+7
c #
source share
6 answers

typeof(Class) is the only way to express a type as a literal. When you write Class.SomeField , you mean a static field. When you write typeof(Class).SomeField , you are referencing the field of the Type class object that your class represents.

+4
source share

Animal is just a type name, typeof(Animal ) returns an object of the actual type (an instance of System.Type ). Undoubtedly, it might, possibly, just have the type name return the type object to the code, but this makes the work much more difficult for the compiler / parser (recognizing when the type name means typeof or something else) - hence the existence of the typeof keyword. It also possibly makes the code more readable.

+6
source share

The lack of typeof is ambiguous:

 class foo { public static string ToString() { return "Static"; } } public class Program { private static void Main(string[] args) { Console.WriteLine(foo.ToString()); Console.WriteLine(typeof(foo).ToString()); } } 

foo and typeof(foo) not the same thing and force the compiler to pretend that this is a bad idea, even if we ignore this ambiguity.

+3
source share

Reflection for starters. Many possibilities become available when you can check the type itself, instead of just knowing what it reveals, or that it exists at all.

+1
source share

typeof () allows me to get an instance of a Type object without having to have an instance of the target in hand. This, in turn, allows me to ask questions about the class without having an instance of it.

0
source share

Well, how do you get a System.Type class without instantiating the class in the first place if you are not using the operatore type? Simple, you can not: D

Since you can do a lot of reflection using only System.Type, this operator is very convenient.

0
source share

All Articles