Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.WriteLine("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?

like image 446
MCS Avatar asked Dec 29 '10 15:12

MCS


People also ask

Does null == null?

If you think of it from a programming (i.e. pointer reference) point of view then, yes, two references of null have the same pointer value and, since most of the popular languages will fall back to pointer-equality if no custom equality is defined, null does equal null.

How to use null coalescing operator in c#?

operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.


1 Answers

You can also use (object)a == null

like image 183
Rex M Avatar answered Oct 21 '22 06:10

Rex M