BlackWaspTM
C# Programming
.NET 1.1+

C# Numeric Data Types (2)

The third part of the C# Fundamentals tutorial takes a first look at the numeric data types available to the C# programming language. This article explains how variables are assigned and includes a quick reference to the numeric data types.

Assignment Problems

Definite Assignment

The C# compiler enforces a rule known as definite assignment. This states that a variable may not be read until a value has been assigned. This prevents you from writing code that reads a variable with an undefined value, as this could give unpredictable results.

The following code fails to compile, displaying the error "Use of unassigned variable numberOfArticles".

// Create variable but do not assign a value
int numberOfArticles;

// Try to create a new variable and assign with
// the value from numberOfArticles
int numberToSave = numberOfArticles;

Assignment of Incorrect Type

A second problem that often occurs when assigning values, is attempting to assign a value that is incompatible with the data type declared, or that would involve loss of information. In the following example the integer variable cannot be assigned a value with a decimal element; the decimal would be rounded. This mistake causes an error in the format "Cannot implicitly convert type 'double' to 'int'".

// Invalid assignment to integer variable
int numberOfArticles = 3.5;

The above conversion is not impossible. However, you must explicitly state that you wish to convert the value's data type. Data type conversions are examined later in the tutorial.

Numeric Data Type Reference

I will end this article with a quick reference to the numeric data types. For integer types, the declaration keyword, a description of the type, the range of possible values and the number of bits used to represent the value are given. For non-integers, the scale and the number of digits of accuracy are given, rather than minimum and maximum. This allows you to determine which data type should be used for any numeric variable.

The Boolean type is included, which although not technically numeric, fits well in this table. The Boolean type can hold either true or false. It is named after the mathematician, George Boole.

Integer Data Types

TypeDescriptionMinimumMaximumBits
boolBoolean flagfalsetrue1
byteUnsigned Byte02558
sbyteSigned Byte-1281278
shortSigned Short Integer-32,76832,76716
ushortUnsigned Short Integer065,53516
intSigned Integer-2,147,483,6482,147,483,64732
uintUnsigned Integer04,294,967,29532
longSigned Long Integer-9x10189x101864
ulongUnsigned Long Integer01.8x101964

Non-Integer (Floating Point) Data Types

TypeDescriptionScalePrecisionBits
floatSingle Precision Number±1.5x10-45 to ±3.4x10387 digits32
doubleDouble Precision Number±5x10-324 to ±1.7x1030815 or 16 digits64
decimalDecimal Number±10-28 to ±7.9x102828 or 29 digits128
27 July 2006