RKh
RKh

Reputation: 14159

Can a class implement two interfaces at the same time?

I tried doing something like this:

class Student: IPersonalDetails: IOtherDetails
{
      //Code
}

It gives error. Why I can't implement two interfaces?

Upvotes: 5

Views: 1263

Answers (6)

dexter
dexter

Reputation: 7213

Yes, or like this which of course targets completely different design goal and you could say that in fact it's still only one interface due to polymorphic nature of inheritance, but still:

public interface IEntity 
{
    void DoTask();
}

public interface IExtendedTaskEntity : IEntity
{
    void DoExtendedTask();
}

public class ConcreteEntity : IExtendedTaskEntity 
{

    #region IExtendedTaskEntity Members

    public void DoExtendedTask()
    {
        throw new NotImplementedException();
    }

    #endregion

    #region IEntity Members

    public void DoTask()
    {
        throw new NotImplementedException();
    }

    #endregion
}

Upvotes: -1

Jörg W Mittag
Jörg W Mittag

Reputation: 369604

Yes, a class can definitely implement more than one interface. After all, that is the whole point of interfaces.

Take a look at the error message you are getting. It is not telling you that a class cannot implement more than one interface. It is telling you that have a syntax error.

Upvotes: 0

Liviu Mandras
Liviu Mandras

Reputation: 6627

Yes! You definitely can. You can even implement more than 2. I am not sure if there is a limit on how many interfaces you can implement at a time.

Upvotes: 1

OlimilOops
OlimilOops

Reputation: 6797

Yes it can, have a deep look at your syntax.

Upvotes: 5

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60744

Change it to

class Student: IPersonalDetails, IOtherDetails
{
  //Code
}

Upvotes: 9

Greg Beech
Greg Beech

Reputation: 136717

Use a comma between the interface types, e.g.

class Student: IPersonalDetails, IOtherDetails
{
      //Code
}

Upvotes: 19

Related Questions