Inherited Interfaces In C# - c#

In c sharp abstract methods must be implemented by child class. So my question is when an interface inherits another interface why doesn't it implement all of base interface members.
public interface IShape
{
void Points();
}
public interface ICircle: IShape
{
void IsDrawAble();
}
When i run this program in Visual Studio 2010 and no error came up. By definition ICircle must implement Points function.
Thanks

Interfaces don't implement anything.
An interface simply contains a list of members that concrete classes need to implement.
There would be no point in re-declaring members that were already required by a base interface.
Similarly, an abstract class that inherits another abstract class (or interface) does not need to implement any of its methods.

When you implement ICircle you'll need to implement Points() as well. The following code does not compile:
class MyClass : ICircle
{
void IsDrawAble() { }
}
So what you stated should be : "By definition all implementations of ICircle must implement the IShape members as well"

You answered the question yourself. Because it's an interface. Interfaces are not classes, therefore they don't have to (in fact cannot) implement other interfaces they inherit.

When you create this kind of hierarchy between interfaces, you are defining who implement the Circle interface will also implement IShape. So, for sample:
public class Test : ICircle
{
public void Points()
{
// some code
}
public void IsDrawAble()
{
// some code
}
}
Using it:
ICircle obj = new Test();
obj.Points();
obj.IsDrawAble();
or
IShape obj = new Test();
obj.Points();

An interface represents a contract. They contain only the signatures of methods, properties, events or indexers. An interface doesn't implement at all. A class/struct that implements an interface must implement the members of the interface that are specified in the interface definition.
The hierarchy you have created simply means that whatever implements the ICircle interface also implements the IShape interface.

Related

Why IDisposable is an Interface, not abstract class?

Can we define IDisposable as an abstract class instead of Interface like below. What are disadvantages?
public abstract class absDisposable
{
public abstract void Dispose();
}
public class childClass : absDisposable
{
SqlConnection objConnect = new SqlConnection("connstring");
public override void Dispose()
{
if (this.objConnect != null)
{
this.objConnect.Dispose();
this.objConnect = null;
}
}
}
I wrote that code in the same Interface works, else there is no reason of abstract class with no implementation. This is same way we define Interface, without any implementations.right? However, the question is not the IDisposable only, its about all Interfaces we use. Why don't we simply write the methods we require, why do we go one level more for Implementing Interfaces? Since Interface serves no purpose. We always have to give our own implementations in derived classes, so no question of code re-usability also. And how Interfaces resolve lack of multiple inheritance in c#, if we cannot re-use codes? All I want to know is what situation an Interface proves its presence?
Since C# does not support multiple inheritance, your idea would make it impossible to combine disposability with an existing base class.
Since IDisposable doesn't include any implementation, there is no reason to make it an abstract class.

Why do we need interfaces when abstract classes exist? [duplicate]

This question already has answers here:
Why do both the abstract class and interface exist in C#?
(11 answers)
Closed 9 years ago.
One interviewer has asked me the below question and I couldn't answer:
Why do we need Interfaces when abstract classes exist?
Whatever the methods we are writing in interface those we can write in Abstract class also. Then why do we need interfaces separately?
Can anybody please tell what is the reason?
Advance thanks...
There are several differences,
Abstract classes can have only one parent class, whereas a class can implement several interfaces.
Interfaces cannot contain any implementation, abstract classes can (they can have abstract methods in addition to not abstract methods).
Interfaces are great to focus on a 'view' we can have on a class. This view can be shared by multiple classes implementing the interface.
For instance, DataTable implements IListSource and ISerializable. So, depending on the context, you can view it as a list source to read its data or as a class which instances can be serialized. When you do so, you focus on a specifc view you can have of an instance.
Interface represents a contract, while you can have several implementations of that contract in different (abstract) classes.
public interface IExample
{
void Do();
}
public abstract class DoFirst : IExample
{
public void Do()
{
Console.WriteLine("Doing it the first way");
}
}
public abstract class DoSecond : IExample
{
public void Do()
{
Console.WriteLine("Doing it the second way");
}
}
public class DoFirstConcrete : DoFirst, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with first.");
}
}
public class DoSecondConcrete : DoSecond, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with second.");
}
}
You abstract class is a partial implementation. Interfaces are contracts, to know what your abstract class can do. You need an interface to describe it.
You can implement multiple interfaces, but only inherit from one abstract class.
An interface is an empty shell, there are only the signatures (name / params / return type) of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern
Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It's more about a guy saying "these classes should look like that, and they got that in common, so fill in the blanks!".
Quoted e-satis from here (much more information too):
What is the difference between an interface and abstract class?
You can't inherit from multiple abstract classes, but you can implement multiple interfaces.

Why don't interfaces act like classes?

I have a few questions regarding interfaces.
Why we can't use virtual keyword with Interfaces members
Why we can't use override keyword in derived class from interfaces
Suppose
interface Iface
{
void Func();
}
class Program : Iface
{
static void Main(string[] args)
{
}
public void Func()
{
Console.WriteLine("In func");
}
}
Why I need to use public on member functions in derived class from interface i.e. in Func() definition? If I am not using public keyword it will result in a compile time error
Can we use static Members in Interface?
Marking a method virtual gives the inheriting class the option to override the respective method. But when inheriting from an interface the implementation is not optional but mandatory. Every interface method is abstract by definition.
You don't override the methods, you implement them. An interface method has no own implementation, there is nothing to override. It just wouldn't make any sense.
Why a C# interface method implemented in a class must be public
No we can't use static methods on an interface
Interfaces don't need that. The implementation can be virtual.
An implementation doesn't need that - there is nothing to override.
You will have to instantiate a Program to call Func. Also there is no concept of static interfaces.
Interfaces dont act like class because, we cant make an object of interfaces if we can make make an object of interfaces to achieve multiple inheritance then we can face diamond problem that occur in the case of multiple inheritance of classes.

How to partially implement a contract in an abstract base class?

I have a interface as follows
public interface IX
{
void MethodA();
void MethodB();
}
I have two method contracts in the interface MethodA and MethodB. I will define set of classes that will implement the above interface. Out of these two methods MethodA is common for all the types that will implement the interface. I can define a abstract class as follows
public abstract class XBase:IX
{
public void MethodA()
{
// Common behaviour implementation
}
public abstract void MethodB();
}
And inherit this class to all the types that need to implement the above interface. It works.
But here in the abstract class i add 'public abstract void MethodB();'. It looks like repetition of the MethodB contract.
Why C# does not permit partial interface implementation if the class is abstract?. The above interface has only two methods. suppose one interface has 10 methods and 5 are common functionality and 5 are not, we are forced to add the 5 methods that are not common in the abstract class?
Because the C# language specification says so. Chapter 13.4.7:
Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class.
Why the C# designers chose to specify the language like this is probably best answered by Eric Lippert. I'd personally guess at reducing the odds that unintended method hiding occurs, producing error messages that are very hard to interpret. I would personally have been more comfortable requiring the use of the overrides keyword for the interface method implementation. But they chose not to.
The reason it doesn't support this is because your superclass doesn't fulfil the contract. The only way for an abstract class to force implementation on its subclasses is to define abstract methods.
If you don't want the abstract class to have those abstract methods defined then you have to tell the subclasses to implement the interface instead.
Question would have to be, why would it be a problem having 5 abstract methods on your superclass?
Interfaces do pass along the contract requirement to each other, so as far as you have IFoo and IBar : IFoo, then classes inheriting from IBar must implement both interfaces, as clearly IBar cannot implement the members of IFoo itself. Why this behavior could not be extended to abstract base classes, I don't know. I'm sure there is a good reason, and since Hans posted the spec, it's obviously intentional.
As a please do not try this at home approach, you could do something like
class Derived : Base, IFoo
{
public void MethodB()
{
}
}
abstract class Base
{
public Base()
{
if (!(this is IFoo))
throw new InvalidOperationException("must implement IFoo");
}
public void MethodA() { }
}
interface IFoo
{
void MethodA();
void MethodB();
}
Which has the abstract base implement the methods it wants and then force the derived classes to implement the rest by enforcing that the derived classes implement the interface. The derived classes would then be responsible for implementing the methods that are not already in the base class. The problem with this approach is that this is a runtime requirement, not compile time.
How would you handle a situation where you have
interface IFoo {
void MethodA();
void MethodB();
}
abstract class Base: IFoo {
public void MethodA() {}
// MethodB gets implicitly generated
}
class Derived: Base {
public void MethodB() {}
}
Could you then do this:
Base myBase = ...
myBase.MethodB();
Ok you could, since MethodB is implicit. But what if you would later decide to remove the interface IFoo from the Base class? You just broke the Base's contract..Solution would be that generated methods would be explicit interface implementations, but that brings another kind of pain.
You can switch from 'abstract' to 'virtual' in the method declaration and provide an assertion:
public abstract void MethodB();
becomes
public virtual void MethodB()
{
Contract.Require( your condition );
}
I don't think abstract class or interface is doing any injustice in your scenario rather as per SOLID principles (specifically: Interface Segregation Principle) : https://msdn.microsoft.com/en-us/library/dn178470(v=pandp.30).aspx
It says large interfaces should be split into smaller and more specific ones so that client classes are not forced to implement methods they do not use at all. Utilizing this principle would solve your problem.

new word in interfaces in c#

using System;
namespace random
{
interface IHelper
{
void HelpMeNow();
}
public class Base : IHelper
{
public void HelpMeNow()
{
Console.WriteLine("Base.HelpMeNow()");
}
}
public class Derived : Base
{
public new void HelpMeNow() ///this line
{
Console.WriteLine("Derived.HelpMeNow()");
}
}
class Test
{
public static void Main()
{
Derived der = new Derived();
der.HelpMeNow();
IHelper helper = (IHelper)der;
helper.HelpMeNow();
Console.ReadLine();
}
}
}
the new keyword in the commented line is a little confusing for me. It jsut mean it overrides the implementation of method in base class.
Why not use override keyword?
It's not really overriding it, it's shadowing it. Given a reference to a Derived object, Base's HelpMeNow function will not be accessible1, and derivedObject.HelpMeNow() will call Derived's implementation.
This is not the same as overriding a virtual function, which HelpMeNow is not. If a Derived object is stored in a reference to a Base, or to an IHelper, then Base's HelpMeNow() will be called, and Derived's implementation will be inaccessible.
Derived derivedReference = new Derived();
Base baseReference = derivedReference;
IHelper helperReference = derivedReference;
derivedReference.HelpMeNow(); // outputs "Derived.HelpMeNow()"
baseReference.HelpMeNow(); // outputs "Base.HelpMeNow()"
helperReference.HelpMeNow(); // outputs "Base.HelpMeNow()"
Of course, if the above is not the desired behavior, and it's usually not, there are two possibilities. If you control Base, simply change HelpMeNow() to virtual, and override it in Derived instead of shadowing it. If you don't control Base, then you can at least fix it halfway, by reimplementing IHelper, like so:
class Derived : Base, IHelper{
public new void HelpMeNow(){Console.WriteLine("Derived.HelpMeNow()");}
void IHelper.HelpMeNow(){HelpMeNow();}
}
This version of Derived uses what's called explicit interface implementation, which allows you to satisfy the contract of implementing an interface without adding the implementation to your class's public interface. In this example, we already have an implementation in Derived's public interface that's inherited from Base, so we have to explicitly implement IHelper to change it2. In this example, we just forward the implementation of IHelper.HelpMeNow to our public interface, which is the shadow of Base's.
So with this change, a call to baseReference.HelpMeNow() still outputs "Base.HelpMeNow()", but a call to helperReference.HelpMeNow() will now output "Derived.HelpMeNow()". Not as good as changing Base's implementation to virtual, but as good as we're gonna get if we don't control Base.
1Exception: it is accessible from within methods of Derived, but only when qualified with base., as in base.HelpMeNow().
2Notice that we also have to declare IHelper as an interface the class implements, even though we inherit this declaration from Base.
In general, if interface IBase implements a member DoSomething, and IDerived inherits/implements Ibase, it expected that IDerived.DoSomething will be synonymous with IBase.DoSomething. In general, this is useful since it saves implementers of the class from having to provide redundant implementations. There are, however, some cases where a derived interface must implement a member which has the same name as a member in the base interface, but which will have to be implemented separately. The most common such situations are (1) the derived method will have a different return type from the base type, or (2) the base interface(s) implements a ReadOnly and/or WriteOnly property(s) with a certain and the derived type should implement a Read-Write property. For whatever reason, if interface IReadableFoo provides a read-only property Foo, IWritableFoo provides a write-only property Foo, and interface IMutableFoo simply inherits both, the compiler won't know whether a reference to Foo refers to IReadableFoo.Foo or IWritableFoo.Foo. Even though only IReadableFoo.Foo can be read, and only IWritableFoo.Foo can be written, neither vb.net nor C# can resolve the overload unless one implements a new read-write property Foo which handles both.

Categories