Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading == operator for null

I have a class called Message which overloads these operators:

public static bool operator ==(Message left, Message right)
public static bool operator !=(Message left, Message right)

public static bool operator ==(Message left, string right)
public static bool operator !=(Message left, string right)

public static bool operator ==(string left, Message right)
public static bool operator !=(string left, Message right)

I want the == and != operators keep comparing references of the types other than String and Message but,

var message = new Message();
var isNull = message == null;

gives me this:

The call is ambiguous between the following methods or properties: 'Message.operator ==(Message, Message)' and 'Message.operator ==(Message, string)'

I know it's because both Message and String are reference types and they both can be null, but I want to be able to use == opreator for checking whether the message is null.

Can I overload == for null values? I tried overloading it for object and call object.ReferenceEquals(object, object) in the overload but that didn't help.

like image 489
Şafak Gür Avatar asked Sep 24 '12 07:09

Şafak Gür


1 Answers

Provide an implementation for operator ==(Message left, object right) and check the type of right to see whether it is null, a string or a Message.

Alternatively, define an implicit constructor for Message that takes a string. See Operator overloading and different types for an example.

like image 131
akton Avatar answered Oct 19 '22 13:10

akton