On a few separate occasions, I have tried to coax the declared type out of a variable, relatively far from its declaration, only to find out that typeof(T) only works on type names.
I was wondering if there would be any breaking changes to allow typeof(variable) as well.
For example, with this code:
class Animal { /* ... */ }
class Goat : Animal { /* ... */ }
/* ... */
var g = new Goat();
Animal a = g;
Console.WriteLine(typeof(Goat));
Console.WriteLine(typeof(Animal));
Console.WriteLine(g.GetType());
Console.WriteLine(a.GetType());
You get something like:
Goat
Animal
Goat
Goat
Why is it not possible to do this:
Console.WriteLine(typeof(g));
Console.WriteLine(typeof(a));
Goat
Animal
I have given the spec a cursory glance, and can’t find any conflict. I think that it would clear up the question ‘Why this type?’ when using the typeof operator.
I know that the compiler is capable, here. An implementation using extension methods is actually trivial:
public static Type TypeOf<T>(this T variable)
{
return typeof(T);
}
But that feels dirty, abusing the type-inference of the compiler.
Suppose it’s allowed: