i want to understand why the C# language decided to make this test expression as an error.
interface IA { }
interface IB { }
class Foo : IA, IB { }
class Program
{
static void testFunction<T>(T obj) where T : IA, IB
{
IA obj2 = obj;
if (obj == obj2) //ERROR
{
}
}
static void Main(string[] args)
{
Foo myFoo = new Foo();
testFunction(myFoo);
Console.ReadLine();
}
}
In the testFunction, i can make an object called obj2 and set it to obj implicitly without casting it. But why cant i then check the two objects to see if they are the same, without casting it? They obviously implement the same interface, so why is it an error?
You can check to see if they're the same object by using Object.ReferenceEquals
or Object.Equals
.
However, since your constraints (IA
and IB
interfaces) don't enforce that the type is necessarily a reference type, there's no guarantee that the equality operator can be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With