Search code examples
c#castingintdoubledivide

Divide 2 ints and get a double in C#


I am a beginner. Both situations below deliver the same output, but are they exactly the same when compiling? if not, in which case the use of one or the other is preferable?

        int num1 = 1001;
        int num2 = 505;
        double num11 = num1;


        double result1 = num11 / num2;
        double result2 = (double)num1 / num2;   //  or (double)num1 / (double)num2;

        Console.WriteLine("result1 = " + result1);
        Console.WriteLine("result2 = " + result2);


        /* Output:
        result1 = 1.98217821782178
        result2 = 1.98217821782178
        */

Solution

  • In the first version, an implicit cast is called to convert num1 to a double. In the second case, you use an explicit cast to do the same. Both approaches are the same in this case but implicit and explicit casts do not need to be the same.

    I think the explicit cast is preferable simply because it is clearer to read what is happening and does not require the initialization of a new variable.