izb
izb

Reputation: 51771

Can I omit interface methods in abstract classes in C#?

I'm a Java developer who's trying to move into C#, and I'm trying to find a nice equivalent to some Java code. In Java, I can do this:

public interface MyInterface
{
    public void theMethod();
}

public abstract class MyAbstractClass implements MyInterface
{
    /* No interface implementation, because it's abstract */
}

public class MyClass extends MyAbstractClass
{
    public void theMethod()
    {
        /* Implement missing interface methods in this class. */
    }
}

What would be a C# equivalent to this? The best solutions using abstract/new/override etc all seem to result in 'theMethod' being declared with a body of some form or another in the abstract class. How can I go about removing reference to this method in the abstract class where it doesn't belong, whilst enforcing it's implementation in the concrete class?

Upvotes: 3

Views: 481

Answers (2)

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

You cannot, you would have to do it like this:

public interface MyInterface 
{ 
    void theMethod(); 
} 

public abstract class MyAbstractClass : MyInterface 
{ 
     public abstract void theMethod();
} 

public class MyClass : MyAbstractClass 
{ 
    public override void theMethod() 
    { 
        /* Implement missing interface methods in this class. */ 
    } 
} 

Upvotes: 5

James
James

Reputation: 82096

No you would have to still have the method signature in the abstract class, but implement it in the derived class.

e.g.

public interface MyInterface
{
     void theMethod();
}

public abstract class MyAbstractClass: MyInterface
{
     public abstract void theMethod();
}

public class MyClass: MyAbstractClass
{
     public override void theMethod()
     {
          /* implementation */
     }
}

Upvotes: 2

Related Questions