ZARk
ZARk

Reputation: 63

Method Overloading with objects implementing same interface

I'm stunned that this doesn't even compile. This is a test program of the issue i'm having in a WCF service i'm writing (where basically the client sends the wcf service a list of different tasks, i'm then server-side processing that list of different tasks, and need to run different methods for each obviously).

Compilation error : cannot convert from 'UserQuery.IMyInterface' to 'UserQuery.MyObj1'

public interface IMyInterface{};

public class MyObj1 : IMyInterface{};
public class MyObj2 : IMyInterface{};


public String Process(MyObj1 obj)
{
return "did one";
}
public String Process(MyObj2 obj)
{
return "did two";
}

void Main()
{

    IMyInterface obj = new MyObj1();
    var s = Process(obj);

    s.Dump();
}

Upvotes: 0

Views: 78

Answers (2)

QuantumHive
QuantumHive

Reputation: 5683

Why not use open generics with type constraints? No need for casting, no need for factory classes or anything hacky.

public string Process<T>(T obj)
  where T : IMyInterface
{
    ...
}

Call it like

IMyInterface obj = new MyObj1();
var s = Process(obj);

as intended.

Upvotes: 0

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

You have to expliciltely cast obj to MyObj1 as the compiler does not know that you assign an instance of that class to obj.

IMyInterface obj = new MyObj1();
var s = Process((MyObj1) obj);

The actual type of obj is only known at runtime.

A better appraoch would be two define the method Process on your interface itself:

IMyInterface {
    public string Process();
}

Now your two classes implement this by:

class MyObj1 : IMyInterface {
    public string Process() { return "did one" ; }
}

Thus you do not even have to pass that instance to the method.

Upvotes: 4

Related Questions