
What is numeric promotion in the C# programming language? Unfortunately it has nothing to do with getting a pay raise. Instead, numeric promotion involves how "smaller" types are "promoted" to larger types when they are part of an arithmetic expression.
This C# article explores the concept of numeric promotion. This concept is used by the C# compiler.
The C# language provides predefined unary and binary operators. This refers to expressions that involve one or two numbers (operands). However, these operators require that their operands be of the same type. So to get an int from an addition, you have to use two ints.
Program that shows numeric promotion [C#]
using System;
class Program
{
static void Main()
{
short a = 10;
ushort b = 20;
// Binary numeric promotion occurs here.
// ... a and b become ints before they are added.
int c = a + b;
Console.WriteLine(c);
}
}
Output
30Explanation. In the code, we try to add a short and a ushort. The program compiles and executes correctly, but in the addition expression, both a and b are promoted to the int type. They can then fit into the binary operator for int addition.
short ushort
Possible errors. Numeric promotion fails when you try to change a or b to a long. This is because you cannot implicitly cast a long to an int; data loss would likely occur. If you try this, you will receive this error:
Cannot implicitly convert type 'long' to 'int'.
An explicit conversion exists (are you missing a cast?)
Numeric promotion is an important concept when looking at the implementation of the C# language. The language provides a structured, standardized way of performing arithmetic expressions and numeric promotion is key to this.
Number Examples