Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force all derived classes to implement an abstract method or property?

Tags:

c#

.net

rules

An abstract function must be implemented by all concrete classes.

Sometimes you want to force all derivative classes to implement the abstract function, even derivatives of concrete classes.

class Base { protected abstract Base Clone(); }
class Concrete : Base { protected override Base Clone(){...}; }
class Custom : Concrete {}

I would like the compiler to tell the programmer that the class Custom needs to implement Clone(). Is there way?

like image 391
Hans Malherbe Avatar asked Jul 16 '09 13:07

Hans Malherbe


2 Answers

It's not possible for the compiler to enforce this. You might look at writing your own analysis plugin to Gendarme or FxCop to enforce such requirements.

like image 88
Michael Donohue Avatar answered Sep 27 '22 23:09

Michael Donohue


I would guess you don't really need ALL derived classes to implement the abstract method, but it definitely sounds like you have a bit of a code smell in your design.

If you don't have any functionality in the Concrete.Clone() method, then you can make your 'Concrete' class abstract as well (just be sure to change the name ;-). Leave out any reference of the Clone() method.

abstract class Base { protected abstract void Clone(); }
abstract class Concrete : Base { }
class Custom : Concrete { protected override void Clone() { /* do something */ } }

If you have some basic functionality in the Concrete.Clone() method, but need detailed information from a higher level, then break it out into it's own abstract method or property forcing a higher level implementation to supply this information.

abstract class Base { protected abstract void Clone(); }

abstract class ConcreteForDatabases : Base 
{ 
    protected abstract string CopyInsertStatemement {get;}

    protected override void Clone()
    {
        // setup db connection & command objects
        string sql = CopyInsertStatemement;
        // process the statement
        // clean up db objects
    }
}

class CustomBusinessThingy : ConcreteForDatabases 
{
    protected override string CopyInsertStatemement {get{return "insert myTable(...) select ... from myTable where ...";}}
}
like image 39
John MacIntyre Avatar answered Sep 27 '22 23:09

John MacIntyre