<qg**********@m ailinator.comwr ote:
I am ok with what you are saying, however, it was my impression that
the whole reason for constraining a generic parameter was so that the
compiler could resolve any issues during compiling time.
To some extent. I'd say the reasons are:
1) Allow *more* to be done by the compiler within the type/method,
because it has more information about what the type parameter might
be at execution time.
2) Constrain clients so they'll only use the type/method with
appropriate type arguments.
If the compiler allows the code to compile without a constraint
(therefore allowing the generic parameter to by =3Fclass=3F =3For-
=3Fstruct=3F), then in my opinion it should allow it to compile with a
constraint of =3Fstruct=3F (whether that makes sense or not) otherwise
this is a double standard.
No - it's using the fact that it's got more information to prohibit a
redundant comparison. The comparison *isn't* redundant when the type is
unconstrained, as it will have different results depending on the value
and the type parameter.
If I wanted to know if the generic parameter is a =3Fclass=3F or a
=3Fstruct=3F then I could use =3Ftypeof(T).Is Class=3F.
You could, but I *suspect* it takes longer. In particular, the JIT can
work out that
if (default(T) == null)
will always be false for value types and true for reference types
without knowing anything about the Type class. I would hope that it
would take advantage of that and optimise away the comparison (and
potentially the code within the subsequent block).
Now it *could* do that through knowledge of the IsClass property, but
it's a bit further away from its normal type of optimisation, IMO.
I am still not clear why this is allowed. Am I just not looking a this
the right way?
Would you rather the comparison was prohibited completely for
unconstrained type parameters? While I can't *immediately* think of a
time I've used it, I'm sure I have...
--
Jon Skeet - <sk***@pobox.co m>
Web site:
http://www.pobox.com/~skeet
Blog:
http://www.msmvps.com/jon.skeet
C# in Depth:
http://csharpindepth.com