I was poking around in .NET Reflector, and noticed that for reference types like "String" for example, there is an explicit overload of the "==" operator:
typeof(string).GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public)
returns: System.Reflection.MethodInfo for the "==" operator.
Due to its implementation, you can't do things like:
if("hi" == 3) // compiler error, plus code would throw an exception even if it ran)
However, the same thing works for value types:
if((int)1 == (float)1.0) // correctly returns true
if((int)1 == (float)1.2) // correctly returns false
I'm trying to figure out exactly how .NET internally handles the type conversion process, so I was looking for the implementation of op_Equality() in .NET Reflector, but "int" doesn't have one.
typeof(int).GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public)
returns null.
So, where is the default implementation for the "==" operator for value types? I'd like to be able to call it via reflection:
public bool AreEqual(object x, object y)
{
if(x.GetType().IsValueType && y.GetType().IsValueType)
return x == y; // Incorrect, this calls the "object" equality override
else
...
}
Edit #1:
I tried this, but it didn't work:
(int)1 == (float)1; // returns true
System.ValueType.Equals( (int)1, (float)1 ); // returns false
Edit #2:
Also tried this, but no love:
object x = (int)1;
object y = (float)1.0;
bool b1 = (x == y); // b1 = false
bool b2 = ((ValueType)x).Equals(y); // b2 = false
I beleive this .Equals operator on ValueType does not work due to this type check (ripped from .NET Reflector):
ValueType.Equals(object obj)
{
...
RuntimeType type = (RuntimeType) base.GetType();
RuntimeType type2 = (RuntimeType) obj.GetType();
if (type2 != type)
{
return false;
}
...