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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With