-1

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
        */
Roblogic
  • 107
  • 3
  • 8
  • 1
    In the third line of you example you are doing [implicit cast](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit-numeric-conversions-table). So actually both approaches are exactly same – Aleks Andreev Mar 22 '19 at 19:47
  • If you want to see the values while running the code, you could always set a breakpoint and step through it to see how it's behaving. https://learn.microsoft.com/en-us/visualstudio/debugger/navigating-through-code-with-the-debugger?view=vs-2017 – Dortimer Mar 22 '19 at 19:48
  • In your simple case, using `num11` (which is num1 converted to a double) is equivalent to using `(double) num1` (which is num1 converted to a double). However, operations involving casting of floating point numbers can become tricky and yield surprising results, as you can read here: https://stackoverflow.com/questions/8795550/casting-a-result-to-float-in-method-returning-float-changes-result. As you are a beginner, this might still be a bit too technical for you, but it is actually good that you exercise caution with regard to the possible effects of floating point casting... –  Mar 22 '19 at 19:49

2 Answers2

2

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.

Hugo
  • 349
  • 3
  • 6
  • 23
1

If any of the arguments in C# is a double, a double divide is used which results in a double. For more information see : https://www.dotnetperls.com/numeric-casts