C# is a strongly-typed language. Before a value can be stored in a variable, the type of the variable must be specified, as in the following examples:
int a = 1; string s = "Hello"; XmlDocument tempDocument = new XmlDocument();
Note that the type must be specified both for simple, built-in types such as an int, and for complex or custom types such as XmlDocument.
C# includes support for the following built-in data types:
Data Type |
Range |
---|---|
byte |
0 .. 255 |
sbyte |
-128 .. 127 |
short |
-32,768 .. 32,767 |
ushort |
0 .. 65,535 |
int |
-2,147,483,648 .. 2,147,483,647 |
uint |
0 .. 4,294,967,295 |
long |
-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807 |
ulong |
0 .. 18,446,744,073,709,551,615 |
float |
-3.402823e38 .. 3.402823e38 |
double |
-1.79769313486232e308 .. 1.79769313486232e308 |
decimal |
-79228162514264337593543950335 .. 79228162514264337593543950335 |
char |
A Unicode character. |
string |
A string of Unicode characters. |
bool |
True or False. |
object |
An object. |
These data type names are aliases for predefined types in the System namespace. They are listed in the section Built-In Types Table (C# Reference). All these types, with the exception of object and string, are value types.
Sample Types of Variables
Let’s take a look at the common variable types that we’ll see in a C# program, and discuss the differences between them, and when you’ll use them.
Here is a table containing the main variable types in C#:
Type Name | Description | Bytes | Data Range | Example |
short | stores smaller integers | 2 | -32,768 to 32,767 | short score = 495; |
int | stores medium sized integers | 4 | -2,147,483,648 to 2,147,483,647 | int score = 450000; |
long | stores very large integers | 8 | –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | long highScore = 4043333; |
byte | stores small unsigned (no + or -) integers | 1 | 0 to 255 | byte color = 55; |
ushort | stores small unsigned integers | 2 | 0 to 65,535 | ushort score = 495; |
uint | stores medium unsigned integers | 4 | 0 to 4,294,967,295 | uint score = 4500000; |
ulong | stores large unsigned integers | 8 | 0 to 18,446,744,073,709,551,615 | ulong highScore = 4043333; |
float | stores smaller real (floating point) numbers | 4 | ±1.5 × 10^−45 to ±3.4 × 10^38, 7 digits of accuracy | float xPosition = 3.2f; |
double | stores larger real numbers | 8 | ±5.0 × 10^−324 to ±1.7 × 10^308, 15 to 16 digits of accuracy | double yPosition = 3.3; |
decimal | real numbers, smaller range, higher accuracy | 16 | ±1.0 × 10^−28 to ±7.9 × 10^28, 28 to 29 digits of accuracy | decimal zPosition = 3.3; |
char | stores a single character or letter | 2 | any single character | char myFavoriteLetter = ‘c’; |
string | stores a sequence of numbers, letters, or symbols | any | a sequence of any character of any length | string message = “Hello World!” |
bool | stores a true or false value | 1 | true or false | bool levelComplete = true; |
—