'Java can combine default implementation from an abstract class and interface in a class. Is there a way to achieve this in C#?
Is there a "smart" way to achieve the same result as in Java when using an interface and abstract class which both implements their own half of a shared interface?
In Java, I'm able to extend an abstract class (AnAbstractClass) and implement an interface (AnotherInterface) which each have a default implementation of their part of an interface (AnInterface), such that I don't have to implement any methods in the class that combines these (See code).
I'm trying to convert Java code to C# while making sure everything is mapped 1-to-1. So I would like to avoid creating new classes as much as possible and that my "Combiner" class doesn't contain any methods.
public class Test{
public interface AnInterface
{
String methodOne();
int methodTwo();
}
public interface AnotherInterface extends AnInterface
{
default int methodTwo()
{
return 2;
}
}
public abstract class AnAbstractClass implements AnInterface
{
public String methodOne()
{
return "1";
}
}
public class Combiner extends AnAbstractClass implements AnotherInterface
{
}
}
Solution 1:[1]
This is accomplishable in C#, but as far as I know there's no smart way to do it as interfaces should in general be kept simple and this would mostly just make the code harder to read and debug.
public interface IAnInterface
{
public string MethodOne();
public int MethodTwo();
}
public interface IAnotherInterface : IAnInterface
{
public static new int MethodTwo()
{
return 2;
}
}
public abstract class AnAbstractClass : IAnInterface
{
public string MethodOne()
{
return "1";
}
public abstract int MethodTwo();
}
public class Combiner : AnAbstractClass, IAnotherInterface
{
public override int MethodTwo()
{
return IAnotherInterface.MethodTwo();
}
}
So I implore you to not do this!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Julian Silden Langlo |
