开发者

compiler warning on (ambiguous) method resolution with named parameters

开发者 https://www.devze.com 2022-12-27 10:26 出处:网络
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 param

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开发者_Go百科 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:)).


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!


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消