Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# implicit conversions and == operator

Some code for context:

class a
{

}

class b
{
    public a a{get;set;}
    public static implicit operator a(b b)
    {
        return b.a;
    }
}

  a a=null;
  b b=null;
  a = b;

  //compiler: cannot apply operator '==' to operands of type tralala...
  bool c = a == b; 

Is it possible to use == operator on different type instances, where one can implicitly convert to another? What did i miss?

Edit:
If types must be the same calling ==, then why

int a=1;
double b=1;
bool c=a==b; 

works?

like image 495
Arnis Lapsa Avatar asked May 21 '09 09:05

Arnis Lapsa


1 Answers

The implicit operator only works for assignment.

You want to overload the equality (==) operator, as such:

class a
{
    public static bool operator ==(a x, b y)
    {
        return x == y.a;
    }

    public static bool operator !=(a x, b y)
    {
        return !(x == y);
    }
}

class b
{
    public a a{get;set;}
    public static implicit operator a(b b)
    {
        return b.a;
    }
}

This should then allow you to compare two objects of type a and b as suggested in your post.

var x = new a();
var y = new b();
bool c = (x == y); // compiles

Note:

I recommmend simply overriding the GetHashCode and Equals method, as the compiler warns, but as you seem to want to supress them, you can do that as follows.

Change your class declaration of a to:

#pragma warning disable 0660, 0661
class a
#pragma warning restore 0660, 0661
{
    // ...
}
like image 79
Noldorin Avatar answered Sep 30 '22 00:09

Noldorin