Something like this should be possible in C#, right?
public void Start ()
{
Class1 x = new Class1 ();
string s = Something (x);
Console.ReadKey ();
}
public string Something (IInterface obj)
{
return foo (obj); // <-- Problem line
}
public string foo (Class1 bar)
{
return "Class1";
}
public string foo (Class2 bar)
{
return "Class2";
}
interface IInterface {}
class Class1 : IInterface {}
class Class2 : IInterface {}
No. Your
foomethods expect eitherClass1orClass2. You’re passing anIInterfacewhich could be eitherClass1orClass2. It won’t compile because the compiler doesn’t know which overloaded method to call. You would have to cast it to one of the types to get it to compile.Alternatively,
IInterfacewould hold thefoomethod that took no arguments and returned which class it was. Then something could take theIInterfaceobject and callobj.foo()Like: