Jason L
Jason L

Reputation: 520

Nested Interface & Abstract Implementation Class

I accidentally came across this in C# 4.0 when I was trying to implement a nested interface with an abstract class:

public class A
{
    public interface InnerInterface
    {
        void Method();
    }
}

public abstract class B : A.InnerInterface
{
    public abstract void A.InnerInterface.Method();
}

public class C : B
{
    public override void A.InnerInterface.Method()
    {
        System.Console.WriteLine("C::A.InnerInterface.Method()");
    }
}

Unfortunately the above code fails to compile, with the following errors:

error CS0106: The modifier 'abstract' is not valid for this item

error CS0106: The modifier 'public' is not valid for this item

error CS0106: The modifier 'override' is not valid for this item

error CS0106: The modifier 'public' is not valid for this item

However if the interface is instead a non-nested interface, like this:

public interface SomeInterface
{
    void Method();
}


public abstract class B : SomeInterface
{
    public abstract void Method();
}

public class C : B
{
    public override void Method()
    {
        System.Console.WriteLine("C::Method()");
    }
}

It compiles OK.

Why the compiler error in the first case? Am I missing something here? Or is it not allowed to implement a nested interface with an abstract class?

Upvotes: 2

Views: 4239

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502506

The problem isn't with the nesting - it's with explicit interface implementation. If you change your "working" example to use:

public abstract void SomeInterface.Method()

you'll see the same problem. You should be able to use implicit interface implementation with a nested interface easily:

public abstract class B : A.InnerInterface
{
    public abstract void Method();
}

public class C : B
{
    public override void Method()
    {
        System.Console.WriteLine("C::A.InnerInterface.Method()");
    }
}

... and if you want to use explicit interface implementation, it should work in the same way for a nested interface as a non-nested one. But you don't write public on explicit interface implementations, and they can't be abstract either (IIRC).

Upvotes: 2

Related Questions