1

Is there any way to enable compiler warnings for implicit conversions in C#?

Recently been debugging for over an hour until I realized I had the following code:

double = int / int;

which didn't quite work as intended. Compiler does not show any warning for it, even at warning level 4. I'm working with Microsoft Visual Studio 2013.

Didii
  • 1,194
  • 12
  • 36

3 Answers3

2

This "problem" is much more of a heuristics issue.

In effect your code was doing the following.

int numerator = ...;
int denominator = ...;
int integerDivide = numerator / denominator;
double result = integerDivide;

At no point was there anything that the compiler should flag as an error. Sure you COULD treat the whole as a warning, but its not in the spirit of how compilers work.

It is possible to add this as a warning on some kind of productivity tool, like Resharper or Roslyn. But it would NEVER be added to the core compiler.

Aron
  • 15,464
  • 3
  • 31
  • 64
  • I understand what the compiler is seeing and that the error happened with the division, but the problem would also not exist if I wanted `result` to be an `int`. The fact is that the compiler implicitly converted an `int` to a `double` and no matter the situation, I'd like a warning for that. C++ compilers do warn users for every implicit conversion from and to basic types. – Didii Apr 10 '15 at 23:32
1

C# already warns about a ridiculous number of safe conversion, but as others observe, it does appear that you are really looking for automatic detection of integer (truncating) division. Unfortunately, it's the same DIV opcode in MSIL, so you need type analysis to detect it. Not impossible, but non-trivial.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

I think this is because assigning the value of an int to a double doesn't require a conversion. If you try the opposite:

double a = 5;
int b = a;

You get a "cannot implicitly convert double to int" error. But if you try what you were doing:

int a = 5;
double b = a;

It works ok.

A double has a higher maximum (and presumably lower minimum) than an int, so there's no conversion necessary, so you shouldn't experience any side effects of assigning a double an int, so there's no need for an error. I notice that even with the strictest rule set enabled the code analysis tool in vs2013 doesn't even raise an eyebrow.

Rocklan
  • 7,888
  • 3
  • 34
  • 49