Sunday, 18 August 2013



Visual Studio .NET 2012

This tutorial will help you how to initialize Arrays in C#

You can initialize(provide values to array data structure) while declaring the array itself.  Curly braces {} are used to provide the values to the array.

Note   If you do not initialize an array at the time of declaration, then the array members are initialized to the default values for the array type. If you declare the array as a field of a type, it will be set to the default value null when you instantiate the type.

Example: Different ways to Initialize Arrays

Single-Dimensional Array

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

string[] names = new string[3] {"Matt", "Joanne", "Robert"};


You can also omit the size of the array:

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

string[] names = new string[] {"Matt", "Joanne", "Robert"};

You can also omit the new operator if you are initializing the array:

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

string[] names = {"Matt", "Joanne", "Robert"};

Multidimensional Array

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

string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };


You can also omit the size of the array:

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

string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };

You can also omit the new operator if you are initializing the array:

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

string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };


Jagged Array (Array-of-Arrays)

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


You can also omit the size of the first array:

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

-or-

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

Notice that there is no initialization syntax for the elements of a jagged array. 




Arrays Tutorial - DOTNET


Get Ebooks delivered to your email id

Comments

Subscribe to our channel

Facebook

Powered by Blogger.

Home | Contact Us | DMCA | Terms of Service | Privacy | Advertise

Maven Scientists