C# virtual vs. abstract methods

For a long time I automatically created abstract methods for things I wanted to see in all my (data) objects but recently I switched quite a few to virtual, let me show why.

So a few years back I introduced a data layer in my personal projects as duplicate queries everywhere grew out of control. I started out with something like this:

With ReSharper asking to auto generate members and the result was a lot of NotImplementedException’s.

This is fine for most DataObject as those needed Load, Save and LoadAll methods anyway, but.. more and more DataObject’s are actually read only and I never use their Save method.

This enables me to override the method only if neccesary and others throw the default NotImplementedException’s resulting in clean code like:

Leave a Reply

Your email address will not be published. Required fields are marked *