dko
dko

Reputation: 718

Defining operators and testing for null

I have a class in C# where I define the operator ==. The method I have currently throws an object is null exception when testing the following

MyClass a = new MyClass(); if(a==null)....

This is frustrating because in the definition of the operator i can't ask if either parameter is null because it will just go into infinite recursion.

How do I test to see if either parameter is null when defining the == operator.

Upvotes: 1

Views: 91

Answers (2)

dlev
dlev

Reputation: 48596

Use object.ReferenceEquals:

if (object.ReferenceEquals(objA, null)) { ... }

Another option is to cast objA to object:

if ((object)objA == null) { ... }

You may want to consult these guidelines.

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124642

Use Object.ReferenceEquals(objA, null).

Upvotes: 1

Related Questions