Reputation: 57
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 {}
Upvotes: 0
Views: 100
Reputation: 30695
No. Your foo
methods expect either Class1
or Class2
. You're passing an IInterface
which could be either Class1
or Class2
. 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, IInterface
would hold the foo
method that took no arguments and returned which class it was. Then something could take the IInterface
object and call obj.foo()
Like:
interface IInterface
{
public string foo();
}
class Class1 : IInterface
{
public string foo()
{
return "Class1";
}
}
class Class2 : IInterface
{
public string foo()
{
return "Class2";
}
}
public void Something(IInterface obj)
{
return obj.foo();
}
Upvotes: 2
Reputation: 700212
No, where non-virtual calls go is determined at compile time, so you can't call different methods depending on the type at runtime.
What you might be looking for is virtual methods:
public void Start () {
Class1 x = new Class1();
string s = Something(x);
Console.ReadKey();
}
public string Something (BaseClass obj) {
return obj.foo();
}
abstract class BaseClass {
abstract string Foo();
}
class Class1 : BaseClass {
public override string foo () {
return "Class1";
}
}
class Class2 : BaseClass {
public override string foo () {
return "Class2";
}
}
Upvotes: 0
Reputation: 15557
public string Something (IInterface obj)
{
return foo ((Class1)obj);
OR // There's no way compiler to know with method to call.
return foo ((Class2)obj);
}
public string foo (Class1 bar)
{
return "Class1";
}
public string foo (Class2 bar)
{
return "Class2";
}
Upvotes: 1