TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Numeric Promotion

This C# article explores the concept of numeric promotion. This concept is used by the C# compiler.

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf