Airhead Airhead - 1 month ago 4
C# Question

C#: Better way to override an abstract method in which the overridden method ignores some of its arguments

So, I have an abstract class with a method with 3 parameters, which is overridden in a particular base class.

The abstract method is in the following form:

internal override void SummonJonSkeet(string dumbQuestion, int a, int b)
// Call upon Jon Skeet and his followers to correct my ignorant ways.

In most of the subclasses that implement the given method, all 3 parameters are needed to produce a correct result. However, in this particular instance the only valid values of a and b are 0.

Currently what I am doing is just ignoring their values within the method, and providing a warning in the documentation comment for the method, but this just feels...wrong.

There has to be a better way than forcing a programmer (well, me) to insert junk arguments into the method call just to make the compiler happy, while still requiring the use of these arguments for every other subclass that implements the method.

Maybe this is a dumb question, since my solution works, but it just feels like it's not a smart way to do it. For example, some idiot (probably me) shouldn't be able to come along and cause an unhandled exception by inserting some ridiculous number into an argument that isn't used in the first place.


Another option (given that you mentioned the parameters are really coordinates that may or may not be used) could be just to make the values nullable with default values of null.

internal override void SummonJonSkeet(string dumbQuestion, int? a = null, int? b = null)

You'd have to match the abstract definition as well, but this shows the approach.

This allows the sub-classes to call SummonJonSkeet("my question") or SummonJonSkeet("my question", 1, 2) based on its implementation. The sub-classes that expect the values can then check a.HasValue or a != null to throw errors when values does not exist for parameters when expected to have values. To get the primitive value, just call a.Value.