Why does String.Equals(Object obj) check to see if this == null?

Posted by m-y on Stack Overflow See other posts from Stack Overflow or by m-y
Published on 2012-04-16T05:19:00Z Indexed on 2012/04/16 5:28 UTC
Read the original article Hit count: 117

Filed under:
|
|
|
|
// Determines whether two strings match. 
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] 
public override bool Equals(Object obj)
{
    //this is necessary to guard against reverse-pinvokes and
    //other callers who do not use the callvirt instruction
    if (this == null)
        throw new NullReferenceException();

    String str = obj as String;
    if (str == null) 
        return false;

    if (Object.ReferenceEquals(this, obj)) 
        return true;

    return EqualsHelper(this, str);
}

The part I don't understand is the fact that it is checking for the current instance, this, against null. The comment is a bit confusing, so I was wondering what does that comment actually mean?

Can anyone give an example of how this could break if that check was not there, and does this mean that I should also place that check in my classes?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET