Unable To Overload != , Error 3 The operator 'ConsoleApplication13.pl.operator !=(ConsoleApplication13.pl, ConsoleApplication13.pl)' requires a matching operator '==' to also be defined C:\Users\htg\documents\visual studio 2013\Projects\ConsoleApplication13\ConsoleApplication13\Program.cs 37 28 ConsoleApplication13 .
class Program
{
static void Main(string[] args)
{
pl a ,b,c;
a= new pl();
b=new pl();
a.mark=99;
b.mark=10;
c = a+b;
if (c != b)
Console.WriteLine("is not equal");
else
Console.WriteLine("both are equal");
Console.WriteLine(c.mark);
Console.ReadLine();
}
}
class pl
{
public int mark;
public static pl operator+ ( pl a , pl b) // 1. here It Work's Perfectly At + overloading
{
pl mm = new pl();
mm.mark = a.mark + b.mark;
return mm;
}
public static bool operator!= (pl m , pl n) // 2. unable to overload
{
if (m.mark != n.mark)
return true;
else
return false;
}
}
Yes - C# requires that if you overload the !=
operator, you also overload the ==
operator. From the C# 5 specification, section 10.10.2:
Certain binary operators require pair-wise declaration. For every declaration of either operator of a pair, there must be a matching declaration of the other operator of the pair. Two operator declarations match when they have the same return type and the same type for each parameter. The following operators require pair-wise declaration:
- operator
==
and operator!=
- operator
>
and operator<
- operator
>=
and operator<=
In this case, it looks like you want:
public static bool operator ==(pl m, pl n)
{
if (ReferenceEquals(m, n))
{
return true;
}
if (ReferenceEquals(m, null) || ReferenceEquals(n, null))
{
return false;
}
return m.mark == n.mark;
}
public static bool operator !=(pl m, pl n)
{
return !(m == n);
}
Note how !=
is implemented in terms of ==
- this is almost always the simplest approach to implementing these operators. Implement ==
fully as it's easier to think in terms of positives, and then implement !=
as the inverse. The ReferenceEquals
checks are performed to mean that null == null
is true, but anything non-null is not equal to null. (This is also a common optimization to ensure that x == x
is true without performing any further tests.)
As noted in comments, it's also very unusual to overload ==
and !=
without also overriding GetHashCode
and Equals(object)
; I'd also recommend implementing IEquatable<T>
. You should implement those to be compatible with your ==
operator - the GetHashCode
method would probably be best just returning mark
.
See more on this question at Stackoverflow