-2

I have seen on the MSDN site that the == operator will return true if both is value type operands are equal.

To fully understand that I have declared the following structs (which to my knowledge are considered value types in C#), and used the == operator, but for some reason I do not understand, I get the following compilation errors.

Does anyone have any idea why the compiler shows these errors, even though p1 and p2 are clearly equal??

struct Point {
  int m_X;
  int m_Y;  
}

Point p1 = new Point(10, 15);
Point p2 = new Point(10, 15);
Point p3 = p2;
bool equals = (p1 == p2); // Compile Error 
bool equals = (p2 == p3); // Compile Error 
bool equals = p1.Equals(p3); 
bool equals = p1.Equals(p2); 

Thanks!

pascalhein
  • 5,700
  • 4
  • 31
  • 44
Steinfeld
  • 649
  • 2
  • 10
  • 20

1 Answers1

7

Its a compile error in C# since this implementation is not provided for structs.

To get this functionality you can overload the == operator.

public static bool operator ==(Point a, Point b)
{
    // Return true if the fields match:
    return a.m_X == b.m_X && a.m_Y == b.m_Y;
}

And while you are at it you can also check out the guidelines here : http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

basarat
  • 261,912
  • 58
  • 460
  • 511