Skip to content

Instantly share code, notes, and snippets.

@John-Paul-R
Last active November 19, 2023 00:14
Show Gist options
  • Save John-Paul-R/40ef1b86a376f2838a3fa6fdab9c7cc7 to your computer and use it in GitHub Desktop.
Save John-Paul-R/40ef1b86a376f2838a3fa6fdab9c7cc7 to your computer and use it in GitHub Desktop.
C#: math, types, and numeric promotion

doing an operation on two numbers will give you a different output type depending on what the types of the operands are.

  • an "operation" is something like "addition" (+) or division (/).
  • an "operand" is one of the things you're doing the operation on.

for example, in 3 - 2, 3 is the first operand, 2 is the second operand, and subtraction (-) is the operation.

For our case, we're working with 2 types:

  • doubles (your decimal values 2.0. "double" is short for "double-precision floating point" number)
  • int An integer! It can't represent decimals. If you convert a decimal like 2.5 into an int with a cast (int)2.5, it truncates to 2, meaning you lose the decimal!

Now, when you go to do math with ints, particularly division, the fact that they can't represent decimals matters!

  • If you do 3/4, you'll get 0, even though the real-world answer is 0.75! Whatever decimal part would be left over always disappears if both operands are integers.
  • If you were to do the same with doubles, however, things work fine! You can try it by appending d or .0 to the end of your numbers to make them doubles. (3d/4d yields 0.75!)

Now, when one operand is an int, and the other is a double, things get interesting. The designers of C# had to make a decision: When do you math with two different types, how do you choose what the type of the result is? They chose to keep the type with greater precision. (The type with greater precision is the type that lets you get more specific with your values, in this case, double is the winner!)

So, for this reason, any time you do 2d + 3 or 3/4d, you'll get a double as your result, and you'll have a decimal!


This idea is sometimes referred to as "Numeric Promotion". You can read about all the places it happens in C# in this article.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment