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:

public abstract class DataObject
{
  public abstract void Load(int id);
  public abstract void Save();
  public abstract void LoadAll();
}

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

public class User : DataObject
{
  public override void Load(int id)
  {
    throw new NotImplementedException();
  }
  public override void Save()
  {
    throw new NotImplementedException();
  }
  public override void LoadAll()
  {
   throw new NotImplementedException();
  }
}

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.

public abstract class VirtualDataObject
{
  public abstract void Load()
  {
    NotImplementedException();
  }
  public virtual void Save()
  {
    NotImplementedException();
  }
  public virtual void LoadAll()
  {
    NotImplementedException();
  }
}

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

public class Log : DataObject
{
  public override void LoadAll()
  {
    // query
  }
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.