Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this test expression an error?

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?

like image 528
Assassinbeast Avatar asked Nov 27 '22 11:11

Assassinbeast


1 Answers

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.

like image 166
Reed Copsey Avatar answered Dec 10 '22 14:12

Reed Copsey