6

I have the following class with some methods and I would like to use this as a base class of another class.

public class BaseClass 
{
    public string DoWork(string str)
    {
        // some codes...
    }

    // other methods...
}

I don't want this class to be instantiated, but the derived class should still use the original implementation of the methods of its base class.

Is it possible? What should be my modifier?

yonan2236
  • 13,371
  • 33
  • 95
  • 141

2 Answers2

6

Since you don't want this class to be instantiated, make it an abstract class. You can still have implementation on the class.

snippet,

public abstract class BaseClass 
{
    public virtual string DoWork(string str)
    {
        // can have implementation here
        // and classes that inherits can overide this method because of virtual.
    }

    // other methods...
}
John Woo
  • 258,903
  • 69
  • 498
  • 492
6

Make BaseClass abstract:

public abstract class BaseClass 
{
    // Only available to BaseClass
    private string _myString;

    public string DoWork(string str)
    {
        // Available to everyone
        return _myString;
    }

    protected void DoWorkInternal() {
        // Only available to classes who inherit base class
    }
}

This way, you can define your own code within BaseClass - but it cannot be initialized directly, it must be inherited from.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 2
    @Mr.Smith I'm not sure. OP says "but the derived class should still use the original implementation of the methods of its base class". I think he does not want `virtual`. – Paolo Falabella Sep 23 '13 at 10:51