Data Types and Arrays in C#

What are Data Types in C#?

In C#, data types define the type of data that a variable can hold. Each variable must have a defined type, such as an integer, float, or string, which determines what kind of operations can be performed on it.

There are two main categories of data types in C#: Value types and Reference types.

Data Type Ranges

The following table shows the minimum and maximum ranges of some common value types in C#:

Data Type Size (in bytes) Minimum Value Maximum Value
byte 1 0 255
int 4 -2,147,483,648 2,147,483,647
float 4 ~1.5 × 10^-45 ~3.4 × 10^38
double 8 ~5.0 × 10^-324 ~1.7 × 10^308
char 2 U+0000 U+FFFF

Different Types of Data Types

The following table lists the various data types in C#:

Category Data Type Description
Integral Types int Represents a signed 32-bit integer.
long Represents a signed 64-bit integer.
short Represents a signed 16-bit integer.
byte Represents an 8-bit unsigned integer.
Floating Point Types float Represents a 32-bit single-precision floating point.
double Represents a 64-bit double-precision floating point.
Character Type char Represents a single Unicode character.
Boolean Type bool Represents a Boolean value (true or false).
String Type string Represents a sequence of characters.

Arrays in C#

An array is a collection of elements that are of the same type. In C#, arrays are zero-indexed, meaning the first element is at index 0. Arrays can be single-dimensional, multi-dimensional, or jagged (arrays of arrays).

Example of a Single-Dimensional Array:

int[] numbers = { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}
        

Multi-Dimensional Arrays:

C# supports multi-dimensional arrays, where each element is accessed using multiple indices. The most common multi-dimensional array is the two-dimensional array, often represented as a matrix.

Example of a Two-Dimensional Array:

int[,] matrix = new int[3, 3]
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

for (int i = 0; i < matrix.GetLength(0); i++)
{
    for (int j = 0; j < matrix.GetLength(1); j++)
    {
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine();
}