C# Interfaces- only implement an interface in other interfaces

23,187

Solution 1

You can't do this in C# - any class can implement any interface it has access to.

Why would you want to do this? Bear in mind that by declaring an interface inheritance:

public interface InterfaceA {}
public interface InterfaceB : InterfaceA {}

You're specifying that anything implementing InterfaceB also has to implement InterfaceA, so you'll get classes implementing InterfaceA anyway.

Solution 2

First of all, it doesn't make sense to say "implement within other interfaces" because interfaces can't implement anything.

I can see two flawed ways of doing this, sort of.

  1. Make Animated and NonAnimated abstract classes that implement IAnimation. The concrete class below them can still forcibly override your IAnimation methods with the new operator:

    class SomeAnim : Animated
    {
        public new void Foo() { }
    }
    
  2. Use mixins. Keep IAnimated and INonAnimated as interfaces, but don't put any methods in your interface. Instead define extension methods like this:

    static class Ext
    {
        public static void Foo(this IAnim anim)
        {
            if (anim is IAnimated) // do something
            else if (anim is INonAnimated) // do something else
        }
    }
    

again, a bit of a hack. But what you're trying to do indicates design flaws anyway.

Share:
23,187
Andrew Camilleri  'Kukks'
Author by

Andrew Camilleri 'Kukks'

Updated on February 18, 2020

Comments

  • Andrew Camilleri  'Kukks'
    Andrew Camilleri 'Kukks' about 4 years

    I would like to only implement certain interfaces within other interfaces, I don't want them to be able to be inherited directly by a class.

    Thanks in advance!

  • thecoop
    thecoop about 14 years
    Is it then possible to actually implement the top level interfaces, if super-interfaces aren't accessible to the implementing class?
  • Andrew Camilleri  'Kukks'
    Andrew Camilleri 'Kukks' about 14 years
    public interface InterfaceA {} public interface InterfaceB : InterfaceA {} public interface InterfaceC : InterfaceA {} InterfaceA would hold the common [i]rules[/i] that I would be using in InterfaceB and InterfaceC
  • thecoop
    thecoop about 14 years
    re code formatting, see here: meta.stackexchange.com/questions/19624/… You need to indent your code by 8 spaces rather than 4
  • Ben Mosher
    Ben Mosher over 11 years
    I get this: Inconsistent accessibility: base interface 'IBaseInterface' is less accessible than interface 'IDescendantOfBaseInterface'. C# 4.0.