public type modifiers for interface - c#

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.

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.

Implementing an interface

I'm confused about the implementation of interfaces.
According to MSDN ICollection<T> has the property IsReadOnly
-And-
According to MSDN Collection<T> implements ICollection<T>
-So-
I thought that Collection<T> would have the property IsReadOnly.
-However-
Collection<string> testCollection = new Collection<string>();
Console.WriteLine(testCollection.IsReadOnly);
The above code gives the compiler error:
'System.Collections.ObjectModel.Collection<string>' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type
'System.Collections.ObjectModel.Collection<string>' could be found (are you missing a using directive or an assembly reference?)
-While-
Collection<string> testInterface = new Collection<string>();
Console.WriteLine(((ICollection<string>)testInterface).IsReadOnly);
The above code works.
-Question-
I thought classes implementing interfaces had to implement every property, so why doesn't testCollection have the IsReadOnly property unless you cast it as ICollection<string>?
It is probably implementing the property explicitly.
C# enables you to define methods as "explicitly implemented interface methods/properties" which are only visible if you have a reference of the exact interface. This enables you to provide a "cleaner" API, without so much noise.
Interfaces can be implemented in couple of ways. Explicitly and implicitly.
Explicit Implementation: When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface
Implicit Implementation: These can be accessed the interface methods and properties as if they were part of the class.
IsReadonly property is implemented explicitly therefore it is not accessible via class directly. Take a look here.
Example:
public interface ITest
{
void SomeMethod();
void SomeMethod2();
}
public ITest : ITest
{
void ITest.SomeMethod() {} //explicit implentation
public void SomeMethod2(){} //implicity implementation
}

Predefined Interface exposes some method,we are using that method but interface doent have definition part ,then how its working in c#?

Interface exposes some method,we are using that method in class but interface doent have definition part ,then how its working in c#.
For Example
class ProductNameComparer : IComparer
{
public int Compare(object x, object y)
{
Product first = (Product)x;
Product second = (Product)y;
return first.Name.CompareTo(second.Name);
}
}
Here IComparer exposes CompareTo() method, but IComparer doesn't have CompareTo() method definition part, then how its working?
Interface are simply contract which only declares method rather than having implementation part....Class which implements that particular Interface should have implemenation detail.
For instance, You have IAnimal interface and Dog is a class which implements IAnimal interface,
public interface IAnimal
{
void Walk(); // Just declares the method, not implemenation
}
//Class implementing the interface
//must define the method specified in the interface
class Dog : IAnimal
{
public void Walk()
{
Console.WriteLine("Dog can walk");
}
}
In your example, you misunderstood the IComparer interface.
IComparer defines an interface with a Compare() method
whereas
CompareTo() is declared by IComparable interface.
In above code, you have implemented IComparer interface so, you are defining Compare() method details in your ProductNameComparer class.
An interface doesn't have any implementation, it's only a contract for how something should work.
You can't create an instance of an interface, you can only create instances of actual classes (or structs) that implement the interface. If you get a reference to an interface, it points to an actual object that implements the interface.
Any class that implements the interface has to implement all members of the interface, so if you have an actual object that fits the interface, you know that the method is implemented.
You can use an interface without any knowledge of any class that implements it, so you can write code that uses an interface even before there is any actual implementation of the interface.
Here IComparer exposes CompareTo() method, but IComparer doesn't have CompareTo() method definition part, then how its working?
If this is your question that I think you are very much misunderstanding what is going and what "exposed" means.
Using your example:
class ProductNameComparer : IComparer
{
public int Compare(object x, object y)
{
Product first = (Product)x;
Product second = (Product)y;
return first.Name.CompareTo(second.Name);
}
}
Your ProductNameComparer class is implementing IComparer. The requirement classes implementing IComparer is they contain a method with the signature Compare(object x, object y). This is the only thing that your ProductNameComparer is exposing. That is nothing else.
Now you are using CompareTo() within the method, but you are not exposing it publicly. It is difficult to explain in more detail without knowing the definition of Product.Name, but let's assume it is a string.
System.String implements IComparable (among other interfaces), so string has a CompareTo() method. You are simply calling String.CompareTo() in your method, but nothing is exposed.
Interfaces define the contract between types, they don't define the implementation, that's up to the classes implementing the interface.
Consider:
interface IWorkable
{
void DoWork();
}
Then the implementation:
public class GoodWork : IWorkable
{
public void DoWork()
{
//add the implementation here
}
}
You should read a good c# tutorial before beginning to program..
http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners
CompareTo method is not from IComparer but it is the method of your property first.Name which I suppose is a string.

Interface and abstract class protection level methods

I came across a bit of code and am not quite sure why it works or why you'd want to do it this way. I would love it if someone could tear it down for me. I do understand well OOP concepts, I simply have not seen this technique before. Thanks
Here is the example:
public interface IInterface
{
IEnumerable<object> DoSomething();
}
public abstract class MyBase : IInterface
{
protected MyBase()
{
}
IEnumerable<object> IInterface.DoSomething()
{
return DoSomething();
}
protected virtual IEnumerable<object> DoSomething()
{
return new List<object>();
}
}
public class MyClass : MyBase
{
internal MyClass() : base() {}
protected override IEnumerable<object> DoSomething()
{
return new List<object>();
}
}
If you're talking about this line of code:
IEnumerable<object> IInterface.DoSomething()
That's called explicit interface implementation.
That forces consumers to access this method only via the interface,
and not to your class directly.
The above method is not private, it's just not explicitly set as public in code. In fact, with explicit interface implementation, you can't even use access modifiers.
One of the reasons for taking this approach is to force better coding practices. If you're the developer of this class, and you know it should only be accessed via an interface, this is the way to force that to happen.
In C#, explicitly implementing an interface by using a sealed method which does nothing but call a protected virtual method allows derived-classes great flexibility with regard to what they want to do with the interface; the method should be given a name other than the name of the interface method (in the above example, it could perhaps be DoSomething_Prot). Explicit interface implementation makes it impossible for a derived class re-implementation to chain to the base-class implementation, but if the only thing the base-class implementation is doing is chaining to a protected virtual or abstract method, there's no need for a derived class to re-implement the interface. Further, even if the derived class were to re-implement the interface either deliberately or as a result of covariance it would still be able to invoke the "guts" of the base-class implementation using the protected method from the base class.
Putting all the code for the interface implementation in a public virtual method which implicitly implements the interface is better than putting code in an explicit implementation, since derived-class code can generally chain to the private member. Such an approach, however, requires that all derived classes publicly implement the method with the same signature. While it may seem like what one would naturally expect anyway, it isn't always. For example, in the above example a derived class may wish to have its DoSomething method return a type other than IEnumerable<object> (e.g. it might return an IList<Kangaroo>). The method which implements the interfae would still have to return precise type IList<Kangaroo>, but code that knew it was dealing with the derived type could use the return type as an IList<Kangaroo> without a typecast. If the actual code for the method were in a method called DoSomething_Prot(), the derived class could both override DoSomething_Prot and declare a new public IList<Kangaroo> DoSomething(). If the base-class method were called DoSomething(), there would be no way for the derived class to both override it and define a new method with a different return type.
Off the top of my head I'm having trouble of thinking of a practical use for this, but one thing that this accomplishes is that objects of type MyBase or its subclasses do not have a public or internally visible DoSomething() method:
MyClass a = new MyClass();
a.DoSomething(); // Compile error
but the DoSomething() method is visible when the object is used as an IInterface:
void AMethod(IInterface i)
{
i.DoSomething(); // compiles just fine
}
void AnotherMethod(MyBase a)
{
AMethod(a); // as does this
}
Making the non-explicit version protected virtual allows subclasses to override the behavior of the DoSomething() method.
This is a way of implementing a method that cannot be called directly when working with MyBases as MyBases, but can be used when they are being treated as IInterfaces. There's nothing to prevent someone from doing this: ((IInterface)a).DoSomething(); but it seems the hiding is done for semantic reasons.
My take on this is that it is an implementation of the template pattern as described here. Typically you see the template pattern used along with the strategy pattern. In your particular example, users of the IInterface could call the DoSomething
method without regard for how the concrete subclass implemented the method.
This kind of OO programming allows you to take advantage of quite a few other patterns such as the AbstractFactory for creating your concrete subclasses of MyBase which implement IInterface.
The important thing to note is that the two DoSomething methods have nothing to do with each other - they just happen to have the same name.
Basically, you've just got a normal interface that exposes a DoSomething method, so the caller who has a IInterface object can call it. It will then in turn pass the call on to the appropriate implementation of the protected DoSomething method, which can either be from the base class or the derived one.
Explicit implementation like this forces you to code by contract instead of implementation - doesn't really provide any actual protection, just makes it more difficult to accidentally use the wrong type when you declare your variable. They just as easily could have done:
public abstract class MyBase : IInterface {
public virtual IEnumerable<object> DoSomething() {
// blah
}
}
public class MyClass : MyBase {
public override IEnumerable<object> DoSomething() {
// blah
}
}
but that would let you call DoSomething on a variable declared as MyClass or MyBase, which you may not want them to do.

Should I implement interface members explicitly or implicitly?

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.

Categories