How to force sub classes to implement a method

Viewed 52464

I am creating an object structure and I want all sub classes of the base to be forced to implement a method.

The only ways I could think of doing it were:

  1. An abstract class - Would work but the base class has some useful helper functions that get used by some of the sub classes.

  2. An interface - If applied to just the base class then the sub classes don't have to implement the function only the base class does.

Is this even possible?

N.B. This is a .NET 2 app.

5 Answers

And full worker sample with params (.netcore 2.2):

class User{
    public string Name = "Fen";
}

class Message{
    public string Text = "Ho";
}

// Interface
interface IWorkerLoop
{
    // Working with client message
    string MessageWorker(string msg);
}

// AbstractWorkerLoop partial implementation
public abstract class AbstractWorkerLoop : IWorkerLoop
{
    public User user;
    public Message msg;

    // Append session object to loop
    public abstract AbstractWorkerLoop(ref User user, ref Message msg){
        this.user = user;
        this.msg = msg;
    }

    public abstract string MessageWorker(string msg);
}

// Worker class
public class TestWorkerLoop : AbstractWorkerLoop
{
    public TestWorkerLoop(ref User user, ref Message msg) : base(user, msg){
        this.user = user;
        this.msg = msg;
    }

    public override string MessageWorker(string msg){
        // Do something with client message    
        return "Works";
    }
}
Related