Camilo Martin
Camilo Martin

Reputation: 37898

How to comment/document an override in C#?

Sometimes I override methods in base classes. Sometimes I even override them with an empty method, because what I want is to prevent the behavior.

In the past I would write something like this to show the intent of bypassing the base method:

protected override void OnMouseUp(MouseEventArgs e)
{
    // base.OnMouseUp(e);
}

(I know a commented line of code is a bad thing. I used to do it)

But I want to do better:

Upvotes: 4

Views: 2734

Answers (3)

Botz3000
Botz3000

Reputation: 39630

Commenting out the base class call does, in my opinion the exact opposite of making intent clear. People will wonder why the commented line is still there, and whether it might still be of some use because you didn't delete it. So i would remove the commented out line.

You could document the override just like any other method and in the documentation, specify why exactly you left the method empty. You could write the reason into the method body as comment as well, i guess that's a matter of preference.

I think it depends on whether this information is only important for the developer maintaining the code or also for the user of the code (e.g. users of your library). In the case of an event that usually gets called by the operating system only (like in your example), putting it in the summary tag wouldn't really be necessary.

Still, if you need to override methods to disable behavior of the base class, maybe you should reconsider that part of your design. That behavior seems a bit unintuitive to me.

Upvotes: 1

Duane Theriot
Duane Theriot

Reputation: 2185

A comment like

// This method is intentionally blank because 
// we do not want the base class functionality

is much better than

// base.SomeMethod();

The first comment clearly states why you did what you did, and the next developer who comes along won't have to wonder if the call to the base method was commented out accidentally.

If you have control over the base class, it may be better to remove that method and make the class more abstract. Then you can choose to only implement that functionality in child classes where it's needed.

Upvotes: 4

Vlad
Vlad

Reputation: 35594

For documentation, I would just use the built-in documentation tags:

/// <summary>Exiting drag mode on mouse up</summary>
protected override void OnMouseUp(MouseEventArgs e)
{
    ...

For clarifying the intention I would just put a comment like

protected override void OnMouseUp(MouseEventArgs e)
{
    // not calling the base implementation
    ...
}

The line

// base.OnMouseUp(e);

makes an impression that the call is commented out temporarily (and perhaps someone forgot to restore it back)

Upvotes: 6

Related Questions