BlackWaspTM
C# Programming
.NET 1.1+

C# Numeric Data Types

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.

Strong and Weak Typed Languages

C# is a strongly typed language. All variables in a program must be declared as being of a specific type. The variable's behaviour is defined by the chosen type. For example, an integer variable can only contain whole numbers. If a number in an integer variable needs a fractional part, it must first be converted to a different type, possibly being stored in a new variable as a part of the translation.

The alternative to a strongly typed language is a weakly typed language. An example would be VBScript used by many classic ASP developers. In VBScript, the type of the variable is not declared and the behaviour of the variable may appear to change from one line of code to the next.

Variable Declaration and Assignment

A variable can be declared with one line of code, specifying the variable type and its name. In the following code, an integer variable is declared using the data type int.

int numberOfArticles;

A variable can be given a value using the assignment operator, (=). The variable to the left of the operator is assigned the value to the right. The following code shows a variable being declared and assigned a value.

int numberOfArticles;
numberOfArticles = 3;

You do not need to assign a value to a new variable immediately. There may be many lines of code between the declaring a variable and giving it a value. However, if you do wish to declare a variable and assign a value at the same time, this can be achieved in a single statement. For example:

int numberOfArticles = 3;

It is possible to declare multiple variables of the same type in a single line of code. You can also assign the same value to multiple variables in one statement. To complicate things further (or to show the elegance of C#, depending on your viewpoint), these operations can be combined. The following code shows three examples.

// Create multiple variables by separating with commas
int weight, size, quantity;

// Assign the three variable the same value (10)
weight = size = quantity = 10;

// Create three integers and assign their initial values
int weight = 1, size = 2, quantity = 3;
27 July 2006