开发者

How to check for null in the operator== method?

开发者 https://www.devze.com 2023-02-01 21:29 出处:网络
Consider the following class: public class Code : IEquatable<Code> { public string Value { get; set; }

Consider the following class:

public class Code : IEquatable<Code> 
{
    public string Value { get; set; }

    public override bool Equals(object obj)
    {
         return Equals(obj as Code);
    }

    public override bool Equals(Code code)
    {
         if (code == null) return false;
         return this.Value == code.Value;
    }

    public static bool operator ==(Code a, Code b)
    {
         if (a == null) return b == null;
         return a.Equals(b);
    }

    public static bool operator !=(Code a, Code b)
    {
         if (a == null) return b!= null;
         return !a.Equals(b);
    }

    // rest of the class here
}

Now try using the == method:

Code a = new Code();
Code b = new Code();
Console.WriteLi开发者_开发知识库ne("The same? {0}", a==b);

The result is a StackOverflowException because the == method calls itself when it checks for null.

But if I take out the null check:

public static bool operator ==(Code a, Code b)
{
    return a.Equals(b);
}

I get a NullReferenceException!

What's the correct way to define these methods?


You can also use (object)a == null


use System.Object.ReferenceEquals(a, null)


Starting in C# 7, you can simply use the is keyword to do a direct reference comparison. See Thorkil's answer to What is the difference between “x is null” and “x == null”?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号