I’m getting a compilation error on following code:
public abstract class DbHandler<T>
{
public abstract bool Save(T obj);
...
}
and its implementing class:
public class SpaghettiTableDb : DbHandler<SpaghettiTable>
{
public bool Save(SpaghettiTable obj)
{
return false;
}
...
}
The error is :
'SpaghettiTableDb' does not implement inherited abstract member 'SeatPicker.DbHandler<SeatPicker.SpaghettiTable>.Save(SeatPicker.SpaghettiTable)'
But I think it does, so I’m not sure why I’m receiving this error.
(SpaghettiTable is just a class with some properties, nothing more)
Any help?
You need to use the
overridekeyword. Otherwise you’re not implementing the abstract base class and just creating a “new” separate method on the subclass.Think of
abstractmethods just likevirtualmethods that you override. The only difference is that you force subclasses to provide an implementation of that method whereasvirtualmethods provide their own implementation that subclasses can optionally override with their own implementation.EDIT: Additionally, if you want to make your life easier in Visual Studio, you can right-click (or
ctrl+.) on the inheritance declaration and choose “implement abstract class” (or something like that, I don’t have VS with me right now) which will automatically create all the overridden methods for you.public class SpaghettiTableDb : DbHandler<SpaghettiTable> //right-click on "DbHandler"Alternatively, in the empty code space within your class, you can start typing “override”, then the IntelliSense will list all overridable members from the base class and when you pick one it will automatically write a default implementation for you.
EDIT:
Just to extend on what you have in your code, without the
overridekeyword, you are creating a new method that belongs to your subclass and not overriding the base class. When you call that method but from the context of using the base class, it won’t call your subclass implementation since it doesn’t override the base method.Consider the following classes. (I’m using virtual instead of abstract just so it compiles and have it simpler)
Note that
SubClass.AnotherPrintdoes not overrideBaseClass.AnotherPrint.And when you use code like:
Note that through the code,
mySubandmyBaseboth point to the same object, but one is typed asSubClassand the other asBaseClass. When the runtime callsmyBase.Print(), it can easily check the inheritance of the classes and see thatSubClasshas overridden thePrintmethod and calls theSubClassimplementation. However, sinceSubClass.AnotherPrintwasn’t explicitly marked withoverride, the runtime/compiler considers that to be a completely different method with no link to theBaseClass.AnotherPrintmethod. Thus the runtime sticks with the base class implementation. When your instance is typed as theSubClassthough, the compiler does see that you’re pointing to that new method and essentially not to the base implementation.