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 ju
Well, how do you get the System.Type of a class without instantiating the class first, if you don't use the typeof operatore? Simple, you can't :D
Since you can do a lot of reflection stuff with just a System.Type, this operator is very handy.
Not having typeof does cause ambiguity:
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)
are not referring to the same thing, and forcing the compiler to pretend they are is a bad idea, even if we ignore this ambiguity.
typeof() allows me to get an instance of a Type object without having to have an instance of the target object in hand. This in turn lets me ask questions about the class without having an instance of it.
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.
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.
Reflection for starters. Many possibilities become available when you can inspect the type itself, instead of just having to know what it exposes, or that it exists at all.