Search This Blog

Monday, December 6, 2010

overriding Equals in c#

Programmer Question

I am trying to override Equals so that it compares based on a variable ID:



public class OrderID

{
public string ID { get; private set; }

public OrderID(string id)
{
ID = id;
}


public override bool Equals(object obj)
{
if (obj is OrderID)
{
return ((OrderID)obj).ID == ID;
}
else return false;
}

public override string ToString()
{
return ID;
}
}




However when I test this in the following manner it returns false:



static void Main(string[] args)

{

OrderID i1 = new OrderID("Hello");
OrderID i2 = new OrderID("Hello");

bool test = i1 == i2;

Console.WriteLine(test.ToString());

Console.ReadKey();
}




What is the problem? When i try to step through it my override is not even stepped into.



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails