Thursday, 15 October 2015

Single Dimensional Array in C#

Single Dimensional Array

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array - 1.

Single Dimensional array is also called one-dimensional array.

DataType[] VariableName = new DataType[Number];

In the above declaration DataType can be char, int, float, double, decimal, string, etc.

VariableName is the name of the array.

The square brackets [] on the left of the assignment operator are used to let the compiler know that you are declaring an array instead of a normal variable.

The new operator allows the compiler to reserve memory.

The [Number] factor is used to specify the number of items of the list.

Declaring single dimensional array

int[] arr = new int[10];

double numbers = new double[5];

string[] names = new string[2];

Single dimensional array initialization


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

string[] names = new string[] { "Rocky""Sam""Tina""Yoo""James""Samantha" };

You can omit the size of the array, like this:

int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Reena""Prety""Rocky""David");

You can also omit the new operator if you initialize array like this:

int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Reena""Prety""Rocky""David"};

No comments:

Post a Comment