Home > Blockchain >  Create default method for classes implementing the same interface
Create default method for classes implementing the same interface

Time:10-02

As a very simplistic example, suppose I have the following C# classes and code:

public interface IMyInterface
{
    public string MyData { get; set; }
    public int MyValue { get; }
}

public class BaseClass1 { }
public class BaseClass2 { }

public class ClassA : BaseClass1, IMyInterface
{
    public string MyData { get; set; }
    public int MyValue { get; private set; }

    public ClassA(string myData, int myValue)
    {
        MyData = myData;
        MyValue = myValue;
        // SAME, specific, code relating to my interface implementation
    }
}

public class ClassB : BaseClass2, IMyInterface
{
    public string MyData { get; set; }
    public int MyValue { get; private set; }

    public ClassB(string myData, int myValue)
    {
        MyData = myData;
        MyValue = myValue;
        // SAME, specific, code relating to my interface implementation
    }
}

So, ClassA and ClassB both implement the same interface and both have the same, boilerplate code they need to run - In this case, just simply setting the public properties (MyData = myData;...) for the interface they both implement and, because they already inherit from other, different classes, I can't create an abstract class to have them inherit from.

Obviously, this is a very simplistic example, but, supposing all of my implementing classes had some, very specific, boilerplate code they needed to run, how can I make it so that I only have to write the boilerplate code in one location and don't need to write the same code in each implementation?

CodePudding user response:

You could do this with a shared static method:

public static class YourHelper
{
   public static void Initialize(IMyInterface foo, ...) ...
}

Then from the ClassA and ClassB constructors, I would call this Initialize method.

public class ClassA : BaseClass1, IMyInterface
{
    public string MyData { get; set; }
    public int MyValue { get; private set; }

    public ClassA(string myData, int myValue)
    {
        MyData = myData;
        MyValue = myValue;
        MyHelper.Initalize(this, ...);
    }
}

I would avoid using default interface implementation because it would rely on virtual mechanisms and calling virtual stuff in a constructor is discouraged.

  • Related