Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface implementation with different method names

Tags:

c#

.net

oop

I have this interface:

public interface INameScope
{
    void Register(string name, object scopedElement);
    object Find(string name);
    void Unregister(string name);
}

But I want my implementation have different names for the methods. My implementation already has a Register method that has another meaning.

Isn't there a method to make implemented methods have names like "RegisterName", "FindName" or "UnregisterName" instead of having to use the very same names?

like image 600
SuperJMN Avatar asked Aug 27 '15 11:08

SuperJMN


2 Answers

Not quite, but you can use explicit interface implementation:

public class SomeScope : INameScope
{
    void INameScope.Register(string name, object scopedElement)
    {
        RegisterName(name, scopedElement);
    }

    public void Register(...)
    {
        // Does something different
    }

    public void RegisterName(...)
    {
        // ...
    }

    ...
}

I would be very wary of doing this if your existing Register method has similar parameters though - while the compiler will be happy with this, you should ask yourself how clear it's going to be to anyone reading your code:

SomeScope x = new SomeScope(...);
INameScope y = x;
x.Register(...); // Does one thing
y.Register(...); // Does something entirely different
like image 169
Jon Skeet Avatar answered Oct 05 '22 22:10

Jon Skeet


Binding of method implementations to interface methods that they implement is done by method signature, i.e. the name and the parameter list. The class that implements an interface with a method Register must have a method Register with the same signature. Although C# lets you have a different Register method as an explicit implementation, in situations like that a better approach would be to go for the Bridge Pattern, which lets you "connect" an interface to an implementation with non-matching method signatures:

interface IMyInterface {
    void Register(string name);
}

class MyImplementation {
    public void RegisterName(string name) {
        // Wrong Register
    }
    public void RegisterName(string name) {
        // Right Register
    }
}

The bridge class "decouples" MyImplementation from IMyInterface, letting you change names of methods and properties independently:

class MyBridge : IMyInterface {
    private readonly MyImplementation impl;
    public MyBridge(MyImplementation impl) {
        this.impl = impl;
    }
    public void Register(string name) {
        impl.RegisterName();
    }
}

When make changes to one of the sides of the bridge, you need to make the corresponding change in the bridge to be back in business.

like image 43
Sergey Kalinichenko Avatar answered Oct 05 '22 23:10

Sergey Kalinichenko