views:

88

answers:

2

One question regarding whether the following code should yield a compiler warning or not (it doesn't). It declares two methods of the same name/return type, one has an additional named/optional parameter with default value.

NOTE: technically the resolution isn't ambiguous, because the rules clearly state that the first method will get called. See here, Overload resolution, third bullet point. This behavior is also intuitive to me, no question.

public void Foo(int arg) { ... }

public void Foo(int arg, bool bar = true) { ...} 

Foo(42); // shouldn't this give a compiler warning?

I think a compiler warning would be kind of intuitive here. Though the code technically is clean (whether it is a sound design is a different question:)).

A: 

Warnings are to notify programmers of potentially dumb mistakes. This is an area that could generate a dumb mistake, so yes, it should generate a warning. Are you trying to form a petition?

nick
+1  A: 

I disagree that it needs a warning, actually. The main issue is, that code is potentially legitimate, and if that's the case you would have to explicitly disable the warning.

What I mean is, in general when you get a warning, you will be able to change your code to get rid of the warning (and presumably make the code better at the same time). But in this case, it may be that you did it like that intentionally and would not be able to change your code to get rid of the warning.

For example, the "unreachable code" warning is something you can just delete the unreachable code to get rid of the warning. Or the "could not find reference" warning - this is usually a signal that you're going to get "undefined type" errors, but if not then you can simply delete the reference. Or maybe "A previous catch clause already catches all exceptions" warning: in this case, you need to change your code so that either the new clause comes before the catch-all, or remove the catch altogether.

But the point is that in every case when you get a warning, you should change your code, and making the change will always result in "better" code. However, in the case of this question, the call is not ambiguous (as far as the compiler is concerned) and I don't think you can argue that it's always a mistake to write code like that, so therefore there shouldn't be a warning.

If the compiler issued a warning about every case where you do something that's probably not the best idea, then we'd be inundated with warnings!

Dean Harding
Maybe there should be a Code Analysis rule for this ... couldn't find one. Extension methods (which in my eyes is a much less severe case) behave the same way in terms of resolution and (absence of warning). However I do feel the problem I asked about is way more severe of an issue than unreachable code.
FireSnake
Yeah, I think it'd be a good candidate for fxcop or somesuch.
Dean Harding