Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to throw NotImplemented exception in virtual methods?

I have a base class for some plugin-style stuff, and there are some methods that are absolutely required to be implemented.

I currently declare those in the base class as virtual, for example

public virtual void Save
{
    throw new NotImplementedException();
}

and in the descendand I have a

public override void Save()
{
    //do stuff
}

Is it a good practice to throw a NotImplementedException there? The descendand classes could for example be the modules for handling different file formats. Thanks

like image 343
Axarydax Avatar asked May 15 '10 19:05

Axarydax


People also ask

Is it necessary to override a virtual method?

When the method is declared as virtual in a base class, and the same definition exists in a derived class, there is no need for override, but a different definition will only work if the method is overridden in the derived class. Two important rules: By default, methods are non-virtual, and they cannot be overridden.

How do you throw a non implemented exception?

The NotImplementedException exception indicates that the method or property that you are attempting to invoke has no implementation and therefore provides no functionality. As a result, you should not handle this error in a try/catch block. Instead, you should remove the member invocation from your code.


1 Answers

Generally I would expect that your base class would be abstract and simply defer the implementation to the inheriting classes.

public abstract class MyBase
{
    public abstract void Save();
    ...
}

public class MyChild : MyBase
{
     public override void Save()
     {
         ... save ...
     }

     ...
}
like image 95
tvanfosson Avatar answered Sep 29 '22 10:09

tvanfosson