Should I implement interface members explicitly or implicitly? - c#

This question and Eric Lippert's answer got me wondering: How do you decide whether to use an explicit or implicit implementation when implementing methods of an interface?

(personally) I only see a need for explicit implementations when there is a clash between methods with the same signature.
For example, when implementing IEnumerable<T>, you should implement 2 methods GetEnumerator() which have the same signature, except for the return type. So you'll have to implement IEnumerable.GetEnumerator() explicitly:
public abstract class MyClass<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return ...;
}
IEnumerator IEnumerable.GetEnumerator() // explicit implementation required
{
return GetEnumerator();
}
}
Another use for an explicit implementation is if you don't want the method to be called through an object instance, but only through an interface. I personally think this doesn't make much sense, but in some very rare cases, it can be useful.

Philippe's answer is a practical, one, however, there are architectural considerations as well.
Interfaces are used to make classes compatible so that they can be consumed by other objects. If only those consuming objects need the functionality of the interface, then it should be restricted so - by the principle of least privilege. If would be unnecessary to expose that interface method to all other users of the class.
Paul

Another case for explicit interfaces is where the object needs to implement an interface to accept calls from an internal object, but you don't want to expose those as part of your API.

Related

access modifiers for IEnumerable<T> and IEnumerable

I'm a beginner in C#, just a question on IEnumerable and IEnumerable. I saw some code like this:
public class ShoppingCart : IEnumerable<Product>
{
public IEnumerator<Product> GetEnumerator()
{
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() //why 'public' is not needed?
{
return GetEnumerator();
}
}
I understand that first method is to implement the IEnumerator<Product> and second method is to implement IEnumerator since IEnumerator inherits from IEnumerator<Product>, but I don't understand why no 'public' access modifier is required for the second method? the first method does have 'public'.
And since both interfaces have same method signature, so we can see that second method use interfacename.methodname as explicit interface implementation, but why first method doesn't need this? shouldn't it be:
public IEnumerator<Product>.GetEnumerator()
{
...
}
It all comes down to the differences between implicit and explicit implementation of interface members.
An explicitly implemented member doesn't appear on the object unless the object is cast to the implemented interface. If you want someone to be able to call new ShoppingCart().GetEnumerator(), you must have a GetEnumerator method that's not an explicit implementation. Supposing it abides by the contract of one of the implemented interfaces, it'll implicitly implement the method on that interface. In this case, you must specify an access modifier because the main point of declaring the member is to make it available from this specific class. The modifier must be at least as permissive as the interface it's implementing (and it may be more permissive).
When explicitly implementing an interface member, you don't need to (and in fact, you cannot) specify the visibility (e.g. public) because the visibility is already set by the interface itself. Since the object must be cast to that interface in order to access that member, the member isn't considered to have any visibility beyond the visibility of the interface.
The first method in your code could have been explicitly implemented, like this:
IEnumerator<Product> IEnumerable<Product>.GetEnumerator()
{
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<Product>)this).GetEnumerator();
}
But whoever created that class chose to implement it implicitly so it would be available without having to first cast ShoppingList to an IEnumerable<Product>. Notice how this made the other method's implementation easier, because they could simply call this.GetEnumerator() without having to cast this first.
But since the second method only differs from the first by return type, it's impossible to implement both methods implicitly. It's common practice to implement the non-generic IEnumerable interface explicitly in these cases.

Giving IFoo.Foo() an implementation via extension method

I came accross the following code:
public interface IFoo { }
Make IFoo do something via an extension method:
public static FooExtensions
{
public static string Foo(this IFoo foo, string bar)
{
// Do work
return bar;
}
}
Is this a good idea? Why not use an abstract class with a virtual Foo() instead? IFoo could have some contract methods but a consumer gets the Foo() extension method also.
My question is: When is something like this a good idea?
The extension method doesn't "make" IFoo do anything. Extension methods just let you extend a type that's closed... it's generally best used in conjunction with code which you don't have the ability to modify, such as framework types or third-party types.
Another possibility is if you have a lot of logic that's absolutely identical across all implementations of your interface, and you want consumers of your interface to have access to that functionality without having to use a base type. Think of LINQ -- it's implemented via extension methods, and you get all the benefits of it just by implementing IEnumerable.
In this case, you're not gaining anything other than an unnecessary layer of indirection. If IFoo should have the ability to do Foo, add Foo to the interface.
Extention methods is a good idea when you don't want or can't change implementation of the class you are extending. IFoo could be declared in a 3rd party library. Or there might be a lot of code dependent on it so that it is very hard to remake it to an abstract class (maybe some reflection rely on interface).
In general from the usage point of view you should use extention methods when it looks more readable than old-school static methods and anyway you would use static method instead of new class member. When considering extention method vs member, consider static method in helper class vs member and if you select static, then consider if it's better to implement it as extention.
But I often see using extention methods where it really isn't required and usually it makes code less readable. So I wouldn't recommend using them when it's easy and obvious how to avoid them.
When is something like this a good idea?
When you need to teach already existing members which implements this interface with new tricks, like this one from the System.Core assembly:
// System.Linq.Enumerable
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
foreach (TSource current in source)
{
if (predicate(current))
{
return current;
}
}
throw Error.NoMatch();
}
The reason you might want to do this is when you want an interface to provide a method and the implementation of that method can always be done using the other methods and properties in the interface.
An interface (unlike an abstract base class) give you no way to provide a "default" implementation for a method. By using an extension method you can provide such a method without all implementers of an interface having to provide the same repeated implementation code.
However, a major drawback of this approach is that the method in the extension method is effectively sealed - you cannot implement it differently. Sometimes this is ok, sometimes not - YMMV.
An alternative approach to this is as follows:
Specify your interface as usual, but add the method in question to it.
Provide an abstract base class which provides the default code for the method in question.
Derive from the abstract base class when you want to provide an implementation of this interface.
Another reason you might want to use an extension method is when you either cannot change the existing interface (because it is third-party, for example) or when you don't want to (because it would break existing code).
Extension methods are merely syntax sugar which allow you to change fun(t, x) into t.fun(x). They're useful for discovery (intellisense), or when you want to compose fluent pipelines of functions which follow a "more intuitive" left to right style, rather than right to left. Eg f(x).g(y).h(z) versus h(g(f(x),y),z).
There's not really any downside to using them other than cluttering intellisense.
This is a good idea when you want to give this implementation to any object which implement that interface, regardless of what implementation is that.
An abstract class provide that implementation only to its derived classes.
If that interface is yours, or, you have a single base-abstract class that implements that interface, and it's safe to assume that no implementations which doesn't derive from that class would be in your code - it would be a good idea to implement that functionality in that abstract class (but, you'll have to cast to that abstract class, to use that method, which makes the interface somehow redundant).
However, if you want to provide an implementation (of that method) to all types which implement that interface, regardless of their actual implementation - an extension method would be a better idea.
Moreover, a class can only derive from a single class - which means that by deriving from that abstract class, you cannot derive from any other class. So, if you'll have multiple inheritance chains which implements that interface, the only solution to provide that method to all of them (directly), without duplication of code, is via an extension (although there other solution to provider the functionality, but it wouldn't be directly: objWhichImplIFoo.Foo()).
BTW, there is another reason to want an extension: if you want it to be callable from nulls. A declared method will always throw a NullReferenceException if the object is null. Because extensions are actually static methods - they can be called upon nulls:
IFoo foo = null;
var something = foo.GetSomethingOrDefault();

what is the difference between explicit and implicit interface implementation in c#

what is the difference between explicit interface and implicit interface implementation in c#/asp.net? in which scenario we can use the explicit interface and implicit interface implementation.
Thanks,
Pradeep
The concept behind implicit and explicit implementation is rather simple:
A member with implicit implementation will be accessible through the interface as well as through the class implementing it
A member with explicit implementation will be accessible through the interface only
As for why and when you would use one or another, it depends. In the case you're implementing more than one interface with the same property/method, explicit implementation is your only option, as it is the only way to know which property/method you're intending to call. Obviously in this scenario you can't have that property/method on the class itself: if there is, it will be class only, and will not match any of the interfaces (which will have their explicit implementation of it).
In other scenarios, it really depends on your design choices and what you're trying to accomplish. If you want to force the caller to access interface members only through interface, and not through class declaration, do an explicit implementation.
Say you have two interfaces, IDoStuff<T> and IDoStuff, which your class implements. They both have a method "GetStuff", but one has the signature T GetStuff(), and the other has the signature object GetStuff().
The problem is that .net will not let you have two methods named the same thing that only differ on the return type. But you need to have both of these methods in your class to satisfy both interfaces. If T is, in fact, an object, then you can use explicit implementation like so.
public T GetStuff()
{
T stuff;
//Stuff Is Got
return stuff;
}
IDoStuff.GetStuff()
{
return (object)GetStuff();
}
Note that because IDoStuff mandates the security requirements of GetStuff, IDoStuff.GetStuff will be public/private/protected/internal based on that interface's declaration.
If you wanted, you could do every implantation explicitly, but the full method name for each would be InterfaceName.MethodName, and that gets a little annoying to read and write. Usually this is only used when you want to implement a method with the same signature multiple times to satisfy several interfaces.

Is the use of explicit interface implementation meant for hiding functionality?

I use interfaces for decoupling my code. I am curious, is the usage of explicit interface implementation meant for hiding functionality?
Example:
public class MyClass : IInterface
{
void IInterface.NoneWillCall(int ragh) { }
}
What is the benefit and specific use case of making this available only explicitly via the interface?
There are two main uses for it in my experience:
It allows you to overload methods by return value. For example, IEnumerable<T> and IEnumerable both declare GetEnumerator() methods, but with different return types - so to implement both, you have to implement at least one of them explicitly. Of course in this question both methods are provided by interfaces, but sometimes you just want to give a "normal" method with a different type (usually a more specific one) to the one from the interface method.
It allows you to implement part of an interface in a "discouraging" way - for example, ReadOnlyCollection<T> implements IList<T>, but "discourages" the mutating calls using explicit interface implementation. This will discourage callers who know about an object by its concrete type from calling inappropriate methods. This smells somewhat of interfaces being too broad, or inappropriately implemented - why would you implement an interface if you couldn't fulfil all its contracts? - but in a pragmatic sense, it can be useful.
One example is ICloneable. By implementing it explicitly, you can have still have a strongly typed version:
public class MyClass : ICloneable {
object ICloneable.Clone() {
return this.Clone();
}
public MyClass Clone() {
return new MyClass() { ... };
}
}
It is not meant for hiding methods but to make it possible to implement two methods with the same signature/name from different interface in to different ways.
If both IA and IB have the operation F you can only implement a different method for each F by explicitly implementing the interfaces.
It can be used for hiding. For example, some classess that implement IDisposable do so explicitly because they also have a Close() method which does the same thing.
You can also use the explicit interface definitions for when you are implementing two interfaces on one class and there is a signature clash and the functionality differs depending on the interface. However, if that happens it is usually a sign that your class is doing too much and you should look at splitting the functionality out a bit.

public type modifiers for interface

When a class implements an interface, the type modifiers for the interface members should be public. Why is there such a restriction?
An interface defines how other objects will communicate with objects of the type that implements that interface; Since other objects can only interact with the public properties and methods of other types, the interface must define those properties and methods as public.
There are two ways of implementing an interface method; the first is implicit implementation - which assumes the public API is exposing the interface methods, and is what you are no-doubt seeing.
However, you can also use explicit implementation:
void IDisposable.Dispose() {
// clean up
}
is a trivial example; this is private, yet satisfies the interface. An explicit implementation always takes precedence over a like-named method on the public API.
In fact, explicit implementation is often necessary, for example to implement IEnumerable<T> - since there are two conflicting GetEnumerator() methods; the following is common:
// public API will be used for implicit IEnumerable<T>.GetEnumerator()
public IEnumerator<T> GetEnumerator() { ... do work ... }
// explicit implementation of IEnumerable.GetEnumerator()
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
So: if you don't want public members; use explicit implementation.
Lets say an Interface can have Private members. When a class inherits the interface, the class will never be able to access the private member. The class will never be able to implement the private member and the program will never get compiled.

Categories