c# - The rules of generics and type constraints -
just out of curiosity, why compiler treat unconstrained generic type differently typeof(object)?
class bar { } class foo { void foo(object thing) { ((bar)thing).tostring(); } } class foo<t> { void foo(t thing) { ((bar)thing).tostring(); } }
in above, casting "t thing" bar results in compiler error. casting "object thing" bar compiler lets me do, @ own risk of course.
what don't see why. in .net object after catch-all , run-time type boxed value or object of type. don't see logical reason there compiler differentiate between 2 cases. best can "the programmer expect compiler type checking generic types, not object". :) there it?
btw, aware can still cast done in foo case, writing
((bar)(object)thing).tostring();
i want understand why compiler this...
the significance here object
. if first illustration anything other object
behave same. basically, saying @ moment here:
(bar)thing
is: "convert t
bar
"; near legal in general case. adding object
create it:
(bar)(object)thing
which "convert t
object
..." - legal, since object
root of managed types; , note may invove box - "...and cast object
bar
" - again; legal @ compile time, , involves type-check ("unbox-any") @ runtime.
for example: suppose t
datetime
...
datetime thing = ... bar bar = (bar)(object)thing;
is valid; sure it'll fail @ runtime, but: scenario need maintain in mind.
c# .net generics
No comments:
Post a Comment