Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces that inherit from a base interface

Tags:

Scenario:

I am using ASP.NET MVC 3 and C#. I have a lot of services that all have an Init() method.

So, I thought, inheritance is my new best friend. I have tried to inherit interfaces from other interfaces.

However, I am running into problems.

What I have done:

As I understand it, one interface can inherit from another interface. i.e, you can do this:

public interface ICaseService : IBaseService {     CaseViewModel ViewModel { get; }      Case Case { get; set; } } 

Where:

public interface IBaseService {     void Init(); } 

So when I derive CaseService from ICaseService I will have to implement the Init() method as well as the Case property and the ViewModel property.

The Problem:

Lets say I now have a controller that has a reference to ICaseService:

private readonly ICaseService service; 

In my actions, I reckon I should be able to do:

public virtual ActionResult MyAction() {     service.Init(); } 

But I get an error message stating that ICaseService 'does not contain a definition for' Init().

Questions:

  1. Why?

  2. Do I have to forget about inheriting interfaces from interfaces and just type out in each interface definition the Init() method?

Note:

The above is a simplified scenario. My "base" interface contains many more definitions than just Init().

like image 671
awrigley Avatar asked Dec 15 '11 14:12

awrigley


People also ask

Can an interface inherit an interface?

Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.

How do you inherit an interface into another interface?

C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.

How many interfaces can an interface inherit?

Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

Can interface be derived from multiple base interfaces?

An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces. Interfaces can contain methods, properties, events, and indexers.


1 Answers

In the inheritance chain, I did a number of dumb things, too many and too dumb to detail here. The valid point is that it works, what was wrong was the chain.

When I looked up on MSDN there was no simple example of this simple technique to back up my understanding, let alone any real documentation of this kind of use of inheritance with interfaces.

like image 54
awrigley Avatar answered Sep 18 '22 22:09

awrigley