This question already has answers here:
C# Interfaces. Implicit implementation versus Explicit implementation
(13 answers)
Closed 9 years ago.
I was always using interfgaces similarly to abstract classes - just to make sure all objects will have consistent external methods etc.
But from MSDN, I do not get that:
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}
static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}
Why there is explicitly mentioned interface name in the method declaration and why it does not work without it?
Also why is the interface being instantionated, shouldn't be just instance of class implementing it?
Why there is explicitly mentioned interface name in the method
declaration and why it does not work without it?
Sometimes it is handy to make your interface explicitly implemented. See this other Stack Overflow questions answer: https://stackoverflow.com/questions/408415/why-explicit-interface-implementation
Also why is the interface being instantionated, shouldn't be just
instance of class implementing it?
They instanciate the ImplementationClass but downcast it to the ISampleInterface Thus preventing themselves from touching non-interface contract guaranteed methods/properties.
Related
This question already has answers here:
Can a C# class call an interface's default interface method from its own implementation?
(3 answers)
Default implementation in interface is not seen by the compiler?
(2 answers)
Closed 5 months ago.
Suppose I have an interface:
interface IFoo
{
void MyMethod()
{
Console.WriteLine("Default implementation here!");
}
}
Suppose, I have a class that implements IFoo:
class Bar : IFoo
{
void MyMethod()
{
// Need something akin to base.MyMethod() here
Console.WriteLine("My custom implementation here!");
}
}
What I want is to first run the default implementation (somewhat alike to base.MyMethod() if IFoo was not an interface but a base class) and then run my custom implementation so that in the end the console output looked like this:
Default implementation here!
My custom implementation here!
This question already has answers here:
Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?
(6 answers)
The difference between abstract classes and interfaces in C# 8 release? [closed]
(3 answers)
What is the difference between an interface with default implementation and abstract class? [duplicate]
(1 answer)
Closed 2 years ago.
With the recent release of C# 8.0 (new feature mentioned here), it allows for providing default method implementation.
While I understand the reason why it's done, I wonder if there is any difference between these 2 concepts?
Thoughts?
To call default interface method You need to cast instance to the interface containing default implementation
You can implement multiple interfaces and cannot inherit multiple abstract classes
It is better to use abstract class for base functionality (provides better inheritance tree logic). And use interfaces with default method implementations to provide small side changes only when this default logic suits for most of implementations (like Microsoft did with their Collection methods).
Also try to not overuse default interface implementations, because this complicates behavior inheritance (you need to search interfaces too, not only classes) from linear to tree.
C++ allows multiple inheritance and without control this aspect can easily make the code unmaintainable.
These are the main differences I see:
Multiple Inheritance
Unlike other languages (like C++), C# does not allow a class to inherit directly from more that one class. On the other hand, a class can implement any number of interfaces, so the new default implementation feature allows you to do something similar to multi-inheritance.
Calling the Default Implementation
If you derive from a class and override a virtual method, you may use the base keyword to call the original implementation. Example:
public abstract class Base
{
public virtual void DoSomething()
{
...
}
}
public class Derived : Base
{
public override void DoSomething()
{
base.DoSomething(); //Here
...
}
}
Constructors and Non-Virtual Members
Abstract classes can declare constructors that the derived class will call. Also, an abstract class can contain non-virtual methods, while an interface can only have overridable (virtual) methods.
This question already has answers here:
Equivalent of Java 1.6 #Override for interfaces in C#
(4 answers)
Closed 8 years ago.
When a base class contains a virtual method, to add a more derived version in a sub class, we have to use override.
AFAICT, this serves two purposes:
We don't accidentally overide a base method
If we mistype the method name when we want to override, we get an error (similar to Java, right?)
However, to my dismay it seems that (in VS2010 / .NET4) it is not possible to use override when implementing an interface method.
Obviously the first bullet is rather a non issue, but the overridekeyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as override.
So, when looking at a class implementation, is there any way other than a // comment to indicate that this method implements the method of a certain interface?
However, to my dismay it seems that (in VS2010 / .NET4) it is not possible to use override when implementing an interface method.
That's because interface methods aren't overridden, they're implemented. It's a seemingly trivial semantic difference, but when we're talking about the use of language semantics are pretty important.
but the overridekeyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as override
Wouldn't it be a bit misleading? override implies that there's a base class definition being, well, overridden. The MSDN documentation defines it as:
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
Interfaces aren't inherited, they're implemented. Again, just semantics, but a pretty important distinction. A class may implement multiple interfaces, the same method may be applied to multiple interface definitions, etc.
Overriding inherited behavior implies:
There is inherited behavior (either with a default implementation in the case of virtual or without in the case of abstract), keeping in mind that C# is a single-inheritance language
The implementation is being overridden (which carries specific distinctions in an inheritance model when the parent class internally invokes that member)
These conditions don't apply to interfaces.
So, when looking at a class implementation, is there any way other than a // comment to indicate that this method implements the method of a certain interface?
Actually, yes. You can explicitly implement an interface. Something like this:
interface IDimensions
{
float Length();
float Width();
}
class Box : IDimensions
{
public float IDimensions.Length()
{
// implementation
}
public float IDimensions.Width()
{
// implementation
}
}
I believe that everything about your concern is summarized by this sentence:
but the overridekeyword would have served as a good simple
documentation and check that the interface methods are actually these
that are marked as override.
Think about what's an interface, and what's an implementer. A class may or may not implement an interface, and can still implement a method with the same signature as an interface. What an interface does is the job of ensuring that some class has the required members to fullfil a contract.
For example, a class Calculator may implement ICalculator and Calculator implements Addition(int, int). But Calculator couldn't implement ICalculator and it could perform an Addition(int, int) anyway.
How do you distinguish both cases? When to use override or not.
Another point: it's nice to implement a class, and fulfill an interface, and stop fulfilling it by just removing it from the class signature after the inheritance colon.
In the other hand, think that the documentation you're looking for is the compiler error telling you that Calculator implements interface ICalculator but it doesn't declare and implement one or more members defined by ICalculator. If the code compiles, you shouldn't care about if a member is of some or other interface. You know that some members are implementations of some interface, because your Calculator signature would look like this: public class Calculator : ICalculator.
Also, there's the case where a implementation member implements it to fulfill more than an interface. What's overriding your implementation? Isn't this more confusing than avoiding override keyword?
Suppose you have these types:
interface ISampleInterface
{
void Method();
}
class A : ISampleInterface
{
public void Method()
{
}
}
class B : A, ISampleInterface
{
void ISampleInterface.Method()
{
}
}
class C : A, ISampleInterface
{
public new void Method()
{
}
}
and use them this way:
ISampleInterface a = new A();
ISampleInterface b = new B();
ISampleInterface c = new C();
a.Method(); // calls A.Method
b.Method(); // calls explicit ISampleInterface.Method
((B)b).Method(); // calls A.Method
c.Method(); // calls C.Method
((A)c).Method(); // calls A.Method
Looks like it is hard to define, which of implementations of Method could be marked as override.
This question already has answers here:
Why ArrayList implement IList, ICollection, IEnumerable?
(4 answers)
Closed 8 years ago.
In .NET Framework 3.5 (C# 3.0) why does System.Hashtable implement both ICollection and IEnumerable when it already implements IDictionary that inherits these two interfaces?
Having these intefaces:
interface IFoo1 {...}
interface IFoo2: IFoo1{...}
There is no difference in terms of compilation between followings:
class MyClass: IFoo2{...}
class MyClass: IFoo2, IFoo1{...}
The second declaration makes it clearer to developers all the interfaces MyClass class implements. So it is easier to have a look at the documentation and see that MyClass implements IFoo1 interface, without digging into IFoo2 interface.
Since the direct base class of Hashtable is System.Object which implements no interfaces, interface re-implementation cannot be relevant here.
Since IDictionary does not hide any of the members it inherits from IEnumerable (for example it does not declare a new method GetEnumerator()), giving distinct implementation for members with the same names also cannot be the reason.
Since neither of the "usual" reasons applies, I have come to think that Hashtable implements both for no particular reason.
Edit:
Not sure this is even an answer.
Above statement was actually wrong. The non-generic IDictionary type does hide a member (overload) GetEnumerator() which it inherits from one of its base interface (non-generic) IEnuemrable. Not sure this is relevant, though. See the two implementations in Hashtable here and here.
New edit:
Actually, if you check the source code (found e.g. here), you see just:
public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable
But as written in an answer in a thread already linked to by a comment by Henrik, in the compiled IL, all base interfaces are still listed explicitly. Hence decompilers that go from the IL in the compiled assembly to pseudo-C#, can't tell the difference.
Final addition:
I really tried to come up with a case involving interface re-implementation where it would matter if you gave also the base interface of an already specified derived interface, but I don't think any exists. This was my try:
interface IBase
{
int Member { get; }
}
interface IDerived : IBase
{
}
class Animal : IBase
{
int IBase.Member
{
get { return 10; }
}
}
class Elephant : Animal, IDerived // try ": Animal, IBase, IDerived" ... ... ... also try ": Animal, IBase"; try ": Animal"
{
public int Member
{
get { return 20; }
}
}
static class Test
{
static void Main()
{
IBase elephantAsIBase = new Elephant();
int readMember = elephantAsIBase.Member;
Console.WriteLine(readMember);
}
}
but turned out not to be an example. Even if only IDerived is specified for Elephant, all interfaces, including IBase are re-implemented. Only if Elephant specifies neither IDerived nor IBase, is re-implementation suppressed.
So Mert's answer and the linked answer are correct, and mine is somewhat off-topic. I'll leave this post for others to learn from, even if it is not strictly relevant to the question posed.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C#: Interfaces - Implicit and Explicit implementation
Would someone explain the differences between these two beasts and how to use them. AFAIK, many pre.2.0 classes were implemented without generic types, thus causing latter version to implement both flavors of interfaces. Is the the only case why one would need to use them?
Can you also explain in depth how to use them.?
Thanks
There is a good and pretty detailed blog post about this.
Basically with implicit interface implementation you access the interface methods and properties as if they were part of the class. With explicit interface implementations you can only access them when treating it as that interface.
In terms of when you would use one over the other, sometimes you have to use explicit interface implementation as you either have a property/method with same signature as the interface or you want to implement two interfaces with the same signatures and have different implementations for those properties/methods that match.
The below rules are from Brad Abrams design guidelines blog.
Do not use explicit members as a security boundary. They can be called by any client who cast an instance to the interface.
Do use explicit members to hide implementation details
Do use explicit members to approximate private interface implementations.
Do expose an alternative way to access any explicitly implemented members that subclasses are allowed to override. Use the same method name unless a conflict would arise.
It's also mentioned in the comments in Brad's blog that there is boxing involved when using explicit implementation on value types so be aware of the performance cost.
In layman's terms, if a class inherits from 2 or more interfaces and if the interfaces happen to have the same method names, the class doesn't know which interface method is being implemented if you use implicit interface implementation. This is one of the scenarios when you would explicitly implement an interface.
Implicit Interface Implementtation
public class MyClass : InterfaceOne, InterfaceTwo
{
public void InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
Explicit Interface Implementation
public class MyClass : InterfaceOne, InterfaceTwo
{
void InterfaceOne.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
void InterfaceTwo.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
The following link has an excellent video explaining this concept
Explicit Interface Implementation
There is one more way to look at it, from the labyrinthine implementation itself, here: http://blogs.msdn.com/cbrumme/archive/2003/05/03/51381.aspx.
But in short, implicit implementation gives you an is-a type conversion, explicit implementation won't be accessible unless the object is explicitly type cast to that interface type.