I have the following code:
class Program
{
static void Main(string[] args)
{
Test test = new Test();
object objTest = test;
Console.WriteLine(test.GetType()); // Output: "OperatorOverload.Test"
Console.WriteLine(objTest.GetType()); // Output: "OperatorOverload.Test"
Console.WriteLine(test == null); // Output: "True"
Console.WriteLine(objTest == null); // Output: "False"
test.Equals(null); // Output: "Hi!"
objTest.Equals(null); // Output: "Hi!"
Console.ReadLine();
}
}
Test looks like this:
class Test
{
public static bool operator ==(Test obj1, Test obj2)
{
return true;
}
public static bool operator !=(Test obj1, Test obj2)
{
return !(obj1 == obj2);
}
public override bool Equals(object obj)
{
Console.WriteLine("Hi!");
return true;
}
}
It appears that operator overloading only works when the type of the variable you're dealing with is the class the operator overload is defined in. I can see why that would be the case, as I'm looking for a safe way of checking whether an object equals null.
My questions are:
Do overloaded operators only work if the type of the variable is the class the operator is defined in (my code tells me yes, but I could be making a mistake)?
Is the following code a safe way of checking whether an object equals null?
SomeClass obj = new SomeClass(); // may have overloaded operators
if ((object)obj == null)
{
// ...
}