Value Types vs Reference Types - Boxing Unboxing

In a custom control, I wrote a general function to handle the object equality. I have used it several times without error. However today I sent a value type instead of a reference type, and some unexpected results occured.

The base class object have some basic methods which other classes override those methods. One of the methods is Equals. Although equals usually compares references of objects,many .Net framework internal classes implement that method like in System.String class it can compare the contents. When we go back to object and call equals method the object polymorphism occurs . This is not true for value types. When we box the value type as a reference type, it creates a new memory space for that. So for each boxing a separate memory block allocated, and the reference comparison normally returns false. Here is the sample how it behaves.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;

public class MyClass
{
	public static void Main()
	{
		string s1 = "can";
		string s2 = "can";
		Console.WriteLine("s1== s2  {0}",s1==s2 ); 
		
		object oo1 = new object();
		object oo2 = new object();
		Console.WriteLine("oo1== oo2  {0}",oo1==oo2 ); 
	
		decimal d1 = 5;
		decimal d2 = 5;
		Console.WriteLine("d1== d2  {0}",d1==d2 ); 
		
		object o1 = d1;
		object o2 = d2;
		Console.WriteLine("o1== o2 {0}", o1==o2);
				
		Console.ReadLine();
	}
}

Below is the output

1
2
3
4
5
s1== s2  True
oo1== oo2  False
d1== d2  True
o1== o2  False
_