While trying to implement a simple singly linked list in C#, I noticed that ==
does not work while comparing two object type variables boxed with an int value but .Equals
works.
Wanted to check why that is so.
The below snippet is a generic object type Data property
public class Node {
/// <summary>
/// Data contained in the node
/// </summary>
private object Data { get; set; };
}
The below code traverses the singly linked list and searches for a value of type object -
/// <summary>
/// <param name="d">Data to be searched in all the nodes of a singly linked list
/// Traverses through each node of a singly linked list and searches for an element
/// <returns>Node if the searched element exists else null </returns>
public Node Search(object d)
{
Node temp = head;
while (temp != null)
{
if (temp.Data.Equals(d))
{
return temp;
}
temp = temp.Next;
}
return null;
}
However, if I replace
temp.Data.Equals(d)
with temp.Data == d
it stops working even though temp.Data
and d
both have the value '3'. Any reasons why ==
does not work on object type variables?
Here's the snippet from the Main function -
SinglyLinkedList list = new SinglyLinkedList();
list.Insert(1);
list.Insert(2);
list.Insert(3);
list.Insert(4);
list.Insert(5);
list.Print();
Node mid = list.Search(3);
I believe since I am passing an int value 3
and the Search method expects an object type, it would have successfully boxed 3 as a object type. However, not sure why ==
doesn't work but .Equals
does.
Is ==
operator overloaded for value types only?