1
Answer

Object.Equals vs. Convert.ReferenceEquals

kevin_ebert

kevin_ebert

21y
2.8k
1
Today, I ran into something I didn't quite expect. I'm sure there is a logical explanation for it so I want to post it and see if anyone can explain the difference to me. I came across a situation when I wanted to see if a public variable inside a struct was null or not. Sample code below: namespace SampleConsole { class Init { [STAThread] static void Main(string[] args) { MyStruct theStruct = new MyStruct(); theStruct.Variable1 = null; try { if (theStruct.Variable1.Equals(null)) Console.WriteLine(".Equals evaluated"); } catch { } try { if (Convert.ReferenceEquals(theStruct.Variable1, null)) Console.WriteLine("ReferenceEquals evaluated"); } catch { } } } public struct MyStruct { public string Variable1; public string Variable2; } } What I found out was that theStruct.Variable1.Equals(null) throws an System.NullReferenceException while Convert.ReferenceEquals(theStruct.Variable1, null) returns true. Well, there is clearly a difference between the two methods. Looking in the MSDN library, I found the following definitions for the two methods: Object.Equals method: Determines whether two Object instances are equal. Convert.ReferenceEquals method: Determines whether the specified Object instances are the same instance. Well, I fail to see the difference in the two definitions. Being the engineer that I am, I thought well let me look up the definition of a System.NullReferenceException and the MSDN library offers: The exception that is thrown when there is an attempt to dereference a null object reference. This doesn't help any either. Any thoughts?

Answers (1)