Search code examples
c#modulo

How come the compiler can't tell the result is an integer


I came across this funny behavior of the compiler:

If I have

    public int GetInt()
    {
        Random rnd = new Random();
        double d = rnd.NextDouble();
        int i = d % 1000;

        return i;
    }

I get an error of: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

which actually makes sense as 1000 can be a double, and the result of the modulo operator might be a double as well.

But after changing the code to:

    public int GetInt()
    {
        Random rnd = new Random();
        double d = rnd.NextDouble();
        int i = d % (int)1000;

        return i;
    }

The error persists.
As far as I can tell, the compiler has all of the information in order to determine that the output of the modulo operator will be an int, so why doesn't it compile?


Solution

  • if d is == to 1500.72546 then the result of the calculation int d % (int)1000 would be 500.72546 so then implicitly casting to an int would result in a loss of data.