11

Can I leave an abstract class that implements interfaces empty and imply that all the methods/properties in the interface are abstract within my class. It appears that I have to write them out again in the abstract class but I really want to avoid this duplication.

My reason is I have a couple of interfaces with different accessors, one public and one internal, that I want to bring together so I have an abstract class that implements them both that can then be extended.

public interface ISomePublicProperties {
    int PropertyOne {get;}
}

internal interface ISomeInternalProperties {
    int PropertyTwo {get;}
}

public abstract class SomeClass : ISomePublicProperties, ISomeInternalProperties {}

But the compiler complains that SomeClass does not implement interface method ISomePublicProperties.PropertyOne and ISomeInternalProperties.PropertyTwo

Is there anyway in C# (I know Java allows this) that I can leave the abstract class empty implementing interfaces?

1
  • Have you tried just creating a virtual stub method to shut the compiler up? Commented Mar 31, 2011 at 3:33

2 Answers 2

16

Nope. In C# the abstract class must fully implement the interface. Note it can implement it with abstract methods and abstract properties. It's one little thing about C# that has always bugged me.

Sign up to request clarification or add additional context in comments.

1 Comment

While you can implement with abstract properties, it seems you can't implement explicitly with abstract properties. The following complains that abstract members cannot be private -- "abstract int ISomePublicProperties.PropertyOne { get; }". Unfortunate.
3

The only way to do it is create virtual properties with no implementation. These are then overridden in your derived classes.

public abstract class SomeClass : ISomePublicProperties, ISomeInternalProperties 
{
    public abstract int PropertyOne { get; }
    internal abstract int PropertyTwo { get; }
}

3 Comments

I think he wants to avoid to have something like public abstract int Property { get; }
Thanks for the responses but I really wanted to avoid the duplication of the interfaces into the abstract class - I just wanted the abstract class to be empty and the extenders of the class to implement the interfaces.
This doesn't work because a virtual property must still have an implementation. You can add setters to them to make them auto properties (depends on the situation if that is a good idea or not), or make them abstract. Making them abstract is the closest thing possible to what the OP wants. Java handles this better than C# :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.