Implement interface method for different structs only once

Viewed 9

Let's not talk about limitation of a struct size, boxing and semantics of having behavior methods in a struct, and just cut to the chase. I have 2 interfaces.

public interface IBase 
{
  int X;
  int GetSomeData();
}

public interface IChild : IBase {}

Also, I have 3 structs. 2 of them implement IBase and 1 implements IChild.

public struct BaseA : IBase 
{
  public int X;
  public int GetSomeData() => X;
} 

public struct BaseB : IBase 
{
  public int X;
  public int GetSomeData() => X; // Duplicate of BaseA, how to implement this method only? once
} 

public struct BaseC : IChild 
{
  public int X;
  public int GetSomeData() => X * 2; // Child may have its own implementation or pick up the base one
} 

As you can see, due to absence of inheritance between structs, each instance of a struct has to implement the same interface every time even when the method implementation itself doesn't change. Also, as you can see, implemented method should have access to some internal fields, so it should be able to access this pointer. The question is in the code, i.e. how to implement method only once and use it in all instances, but still be able to use different implementation in the inherited interface?

Besides obvious answer to use classes that is not an option, here are the others.

Solution with extensions

Define common interface method as extension and unique method as a part of the interface.

public struct BaseA : IBase 
{
  public int X;
  public int GetSomeDataFromInterface() => X
}

public static BaseExtensions 
{
  public static int GetSomeDataFromExtension(this IBase instance)
  {
    return instance.X;
  }
}

Solution with delegates

Define common method elsewhere and assign it to the structs that should have the same implementation.

public struct BaseA : IBase 
{
  public int X;
  public Func<int> GetSomeData();
}

var baseA = new BaseA
{
  GetSomeData = () => X;
};

Mentioned solutions look quite ugly and I was wondering if there is any other way to prevent duplicating code in structs using the same interface?

0 Answers
Related