Enforce that a class can only inherit one interface

G

Guest

Hi

Is it possible in one way or another to enforce that a class only inherit
from one of the derived interfaces of a base interface of some kind. For
example.
public class MyClass2 : IMyInterface1 => OK
public class MyClass2 : IMyInterface1, IMyInterface2 => Error

Regards
/Niklas

public interface IMyInterfacsBase
{
string MyMethod1();
}

public interface IMyInterface1 : IMyInterfacsBase
{
int MyInt1{ get; }
}

public interface IMyInterface2 : IMyInterfacsBase
{
int MyInt1{ get;}
int MyInt2{ get;}
}

public class MyClass2 : IMyInterface1, IMyInterface2
{
private int _MyInt1 = 4;
private int _MyInt2 = 5;

public int MyInt1
{
get { return _MyInt1; }
}

public int MyInt2
{
get { return _MyInt2; }
}

public string MyMethod1()
{
throw new NotImplementedException();
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Niklas said:
Hi

Is it possible in one way or another to enforce that a class only inherit
from one of the derived interfaces of a base interface of some kind. For

First of all, a class do not inherit an interface, it implement it. which is
different.

And no, there is no way I know of to especify that a class can implement at
the most one nterface.

If you substitute interface by class you can be sure of that, as C# ins a
single inheritance language.

why you want to do this anyway?
 
J

Joanna Carter [TeamB]

"Niklas" <[email protected]> a écrit dans le message de (e-mail address removed)...

| Is it possible in one way or another to enforce that a class only inherit
| from one of the derived interfaces of a base interface of some kind. For
| example.
| public class MyClass2 : IMyInterface1 => OK
| public class MyClass2 : IMyInterface1, IMyInterface2 => Error

No, but you can delegate an interface to an aggregated object inside the
main class, so that each interface's behaviour is looked after separately,
even though the class implements more than one interface.

What are you really trying to achieve ?

Joanna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top