0

Assume that I have the following classes with a generic interface:

public class MyClass_1 : IGenericInterface
{
    public void foo()
    {
        bar();
    }
    
    void bar()
    {
        ...
    }
}


public class MyClass_2 : IGenericInterface
{
    public void foo()
    {
        bar();
    }
    
    void bar()
    {
        ...
    }
}



public interface IGenericInterface
{
    void foo();
}

They both have the public "foo" function and it's implementation is the same as well. So I tend to move "foo" into an abstract, shouldn't I?

Now, the problem is, that they call a private function ("bar") which is a class specific implementation. How can I make this function "bar" kind of visible to the possibly generic implementation of "foo"?

E.g.

public abstract class MyGenericClass: IGenericInterface
{
    public foo()
    {
        bar();
    }
}

The goal then would be that the specific class inherit from the generic class:

public class MyClass_1 : GenericClass
{
    private void bar()
    {
        ...
    }
}


public class MyClass_2 : GenericClass
{       
    private void bar
    {
        ...
    }
}
SomeBody
  • 7,515
  • 2
  • 17
  • 33
RadioMan85
  • 337
  • 1
  • 11

2 Answers2

3

Define bar as abstract:

public abstract class MyGenericClass: IGenericInterface
{
    protected abstract void bar();
    
    public foo()
    {
        bar();
    }
}

Then bar can be implemented differently in each subclass, but the base class can be sure it exists:

public class MyClass_1 : GenericClass
{
    protected override void bar
    {
        // ...
    }
}
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
2

Make it an abstract protected method in your base class:

public abstract class MyGenericClass: IGenericInterface
{
    public foo()
    {
        bar();
    }

    protected abstract void bar();
}

Protected means that it will be visible in all derived classes, abstract means that your derived classes have to implement it (if they are not abstract themselves).

SomeBody
  • 7,515
  • 2
  • 17
  • 33