On 15 Feb 2005 08:47:28 -0800, "GlennDoten" <gd****@gmail.com> wrote:
I just happened to be looking through the implementation of the
System.Version class in the SSCLI and one of the constructors starts
like this:
public Version(String version) {
if ((Object) version == null)
throw new ArgumentNullException("version");
Does anyone have any ideas why the string parameter is being cast to an
object prior to checking for null? Is there some circumstance where not
having the explicit cast to object would cause the test for null to not
work as expected?
Yes -- if the object in question is of a type that overrides
operator== and does funny things when comparing to a null reference.
However, such an implementation would be considered defective by any
standard and should be fixed rather than worked around!
But in fact, it's a good idea to cast to object before comparing to
null whenever operator== is overriden by the compared type, even if it
doesn't do funny things. The reason is that it's much faster.
When applied to System.Object the "==" and "!=" tokens directly
translate to a single IL instruction each. But when applied to a type
that overrides operator== method calls are generated instead.
I suspect it's for this latter reason that the object cast exists.
System.String does override operator== to achieve "value type
semantics", as they call it; i.e. two strings are equal if they have
the same contents. The object cast saves a method call.
--
http://www.kynosarges.de