Just out of curiosity, why does the compiler refer to an unlimited generic type, other than typeof (object)?
class Bar { } class Foo { void foo(object thing) { ((Bar)thing).ToString(); } } class Foo<T> { void foo(T thing) { ((Bar)thing).ToString(); } }
In the above example, casting the "T thing" to Bar results in a compiler error. Casting the “thing thing” in Bar, however, is what the compiler allows me to do, at my own risk, of course.
What I do not see is why. In the .net object, after all, is catch-all, and the runtime type can be a boxed value or an object of any type. Therefore, I do not see what is the logical reason for the compiler to distinguish between these two cases. The best I can do is something like “the programmer expected the compiler to conduct type checking with generic types, but not with the object.” :) Is that all?
Btw, I know that I can still get my action done in the case of Foo just by writing
((Bar)(object)thing).ToString();
I just want to understand why the compiler does this ...
source share