Question

I have a class that is a base for some other classes. The class has a virtual method, which is supposed to be overridden in the derived classes. This is how it's defined:

protected virtual TableFormat GetFormat()
{
    throw new NotImplementedException("Implement the format generator in derived class.");
}

Is this good practice? My boss is telling me that NotImplementedException should be only used for auto-generated code, but I refuse to conform to that until he gives a reason for it.

Also, this seems like a good place to have an abstract method in a nonabstract class. Why is this not allowed?

Était-ce utile?

La solution

Is this a good practice?:

IMO, its better to throw NotImplementedException since what else would you return, if you return null, the user of your class would never know that this method has to be overridden. So I would disagree with your boss.

this seems like a good place to have an abstract method in a nonabstract class. Why is this not allowed?

You may see the discussion: Abstract Method in Non Abstract Class

I have a class that is a base for some other classes. The class has a virtual method, which is supposed to be overridden in the derived classes.

Why not define the method as abstract instead of virtual.

Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

BUT

  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration
    simply ends with a semicolon and there are no curly braces ({ })
    following the signature.

Autres conseils

If you mark the method as abstract any implementations of this class will have to define the body. You will need to mark the class as abstract too.

public abstract class MyClass 
{
    protected abstract TableFormat GetFormat();
}

Such methods are a valid way to enforce overriding that method. I think this should be allowed, but your boss might disagree with me.

In fact, if this your class will be instantiated, but the method won't be called, this practice is better than making abstract classes. Also you might try strict type checking in such a method, so that if the current instance is of exactly this class but not a subclass (if it's possible, of course), then the exception is not thrown.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top