C# Numeric PromotionExplore the concept of numeric promotion. This is an algorithm used by the C# compiler.
Numeric promotion. This is a compiler concept. It tells us how "smaller" types are "promoted" to larger types when they are part of an arithmetic expression. This is an important part of the C#.
The C# language provides predefined unary and binary operators. This refers to expressions that involve one or two numbers (operands). 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. Sometimes a number can be implicitly cast.Int, uint
Example: We try to add a short and a ushort. The program compiles and executes correctly.short, ushort
But: In the addition expression, both variables are promoted to the int type. They can then fit into the binary operator for int addition.
C# program that shows numeric promotion
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;
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 an error.Compile-Time Error
Cannot implicitly convert type 'long' to 'int'.
An explicit conversion exists (are you missing a cast?)
Summary. 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.