C#:.NET:Number

.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple Window

Numeric promotion. What is numeric promotion? Sadly it involves no pay raise. Instead, numeric promotion involves how "smaller" types are "promoted" to larger types when they are part of an arithmetic expression.


Example. 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.

C# program that shows numeric promotion

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

30

In this example, we try to add a short and a ushort. The program compiles and executes correctly, but in the addition expression, both variables are promoted to the int type. They can then fit into the binary operator for int addition.

shortushort

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 an error.

Compile-Time Error
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.