Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » C# Language » Working with Arrays in C# .NET

Working with Arrays in C# .NET

This tutorial discusses array programming in C# and .NET. It starts with the discussion of simple arrays and then delves into more complex topics such as jagged and multi-dimensional arrays. In the end, it discusses the Array class and it's methods for searching and sorting an array's items.

Author Rank :
Page Views : 2104923
Downloads : 3092
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ArraysTutorialsWordDoc.zip | ArraysInCSharpSample.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Author Note: The original article was written in Feb 2002. Here I am after 9 years later. Fixed some grammar and code bugs and updated it to .NET 4.0.  BTW, this article is almost reaching 2 million views.

Programming Arrays in C#

Programming C# is a new self-taught series of articles, in which I demonstrate various topics of C# language in a simple step by step tutorial format.

Arrays are probably one of the most wanted topics in C#. The focus of this article is arrays in C#. The article starts with basic definitions of different array types and how to use them in our application. Later, the article covers the Arrays class and its methods, which can be used to sort, search, get, and set an array's items.

Introduction

In C#, an array index starts at zero. That means the first item of an array starts at the 0th position. The position of the last item on an array will total number of items - 1. So if an array has 10 items, the last 10th item is at 9th position.

In C#, arrays can be declared as fixed length or dynamic.

A fixed length array can store a predefined number of items.

A dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.

Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest dynamic array of integer types that does not have a fixed size.

int[] intArray;


As you can see from the above code snippet, the declaration of an array starts with a type of array followed by a square bracket ([]) and name of the array.

The following code snippet declares an array that can store 5 items only starting from index 0 to 4.

int[] intArray;

intArray = new int[5];


The following code snippet declares an array that can store 100 items starting from index 0 to 99.

int[] intArray;

intArray = new int[100];


Defining arrays of different types

In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can define arrays of any type such as double, character, and string.

In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.

The following code snippet defines arrays of double, char, bool, and string data types.

double[] doubleArray = new double[5];

char[] charArray = new char[5];

bool[] boolArray = new bool[2];

string[] stringArray = new string[10];


Initializing Arrays

Once an array is declared, the next step is to initialize an array. The initialization process of an array includes adding actual data to the array.

The following code snippet creates an array of 3 items and values of these items are added when the array is initialized.

// Initialize a fixed array

int[] staticIntArray = new int[3] {1, 3, 5};

 

Alternative, we can also add array items one at a time as listed in the following code snippet.

 

// Initialize a fixed array one item at a time

int[] staticIntArray = new int[3];

staticIntArray[0] = 1;

staticIntArray[1] = 3;

staticIntArray[2] = 5;

 

The following code snippet declares a dynamic array with string values.

 

// Initialize a dynamic array items during declaration

string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" };


Accessing Arrays

We can access an array item by passing the item index in the array. The following code snippet creates an array of three items and displays those items on the console.

// Initialize a fixed array one item at a time

int[] staticIntArray = new int[3];

staticIntArray[0] = 1;

staticIntArray[1] = 3;

staticIntArray[2] = 5;

 

// Read array items one by one

Console.WriteLine(staticIntArray[0]);

Console.WriteLine(staticIntArray[1]);

Console.WriteLine(staticIntArray[2]);

 

This method is useful when you know what item you want to access from an array. If you try to pass an item index greater than the items in array, you will get an error.


Accessing an array using a foreach Loop

The foreach control statement (loop) is used to iterate through the items of an array. For example, the following code uses foreach loop to read all items of an array of strings.

 

// Initialize a dynamic array items during declaration

string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" };

 

// Read array items using foreach loop

foreach (string str in strArray)

{

    Console.WriteLine(str);

}


This approach is used when you do not know the exact index of an item in an array and needs to loop through all the items.

Array Types

Arrays can be divided into the following four categories.

·         Single-dimensional arrays

·         Multidimensional arrays or rectangular arrays

·         Jagged arrays

·         Mixed arrays.

Single Dimension Arrays

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 contiguously starting from 0 to the size of the array -1.

The following code declares an integer array that can store 3 items. As you can see from the code, first I declare the array using [] bracket and after that I instantiate the array by calling the new operator.

int[] intArray;

intArray = new int[3];


Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared.

The following code declares and initializes an array of three items of integer type.

int[] staticIntArray = new int[3] {1, 3, 5};


The following code declares and initializes an array of 5 string items.

string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };

 

You can even directly assign these values without using the new operator.


string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };


You can initialize a dynamic length array as follows:


string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };

 

Multi-Dimensional Arrays


A multi-dimensional array, also known as a rectangular array is an array with more than one dimension. The form of a multi-dimensional array is a matrix.

Declaring a multi-dimensional array

A multi dimension array is declared as following:

string[,] mutliDimStringArray;

A multi-dimensional array can be fixed-sized or dynamic sized.

Initializing multi-dimensional arrays

The following code snippet is an example of fixed-sized multi-dimensional arrays that defines two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items. Both of these arrays are initialized during the declaration.

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

string[,] names = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } };


Now let's see examples of multi-dimensional dynamic arrays where you are not sure of the number of items of the array. The following code snippet creates two multi-dimensional arrays with no limit.


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

string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };


You can also omit the new operator as we did in single dimension arrays. You can assign these values directly without using the new operator. For example:

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

string[,] names = { { "Rosy", "Amy" }, { "Peter", "Albert" } };

 

We can also initialize the array items one item at a time. The following code snippet is an example of initializing array items one at a time.

 

int[,] numbers = new int[3, 2];

numbers[0, 0] = 1;

numbers[1, 0] = 2;

numbers[2, 0] = 3;

numbers[0, 1] = 4;

numbers[1, 1] = 5;

numbers[2, 1] = 6;


Accessing multi-dimensional arrays

A multi-dimensional array items are represented in a matrix format and to access it's items, we need to specify the matrix dimension. For example, item(1,2) represents an array item in the matrix at second row and third column.

The following code snippet shows how to access numbers array defined in the above code.

Console.WriteLine(numbers[0,0]);

Console.WriteLine(numbers[0, 1]);

Console.WriteLine(numbers[1, 0]);

Console.WriteLine(numbers[1, 1]);

Console.WriteLine(numbers[2, 0]);

Console.WriteLine(numbers[2, 2]);

 

Jagged Arrays


Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.

 

Declaring Jagged Arrays

 

Declaration of a jagged array involves two brackets. For example, the following code snippet declares a jagged array that has three items of an array.

 

int[][] intJaggedArray = new int[3][];

 

The following code snippet declares a jagged array that has two items of an array.

 

string[][] stringJaggedArray = new string[2][];

 

Initializing Jagged Arrays

 

Before a jagged array can be used, its items must be initialized. The following code snippet initializes a jagged array; the first item with an array of integers that has two integers, second item with an array of integers that has 4 integers, and a third item with an array of integers that has 6 integers.


// Initializing jagged arrays

intJaggedArray[0] = new int[2];

intJaggedArray[1] = new int[4];

intJaggedArray[2] = new int[6];


We can also initialize a jagged array's items by providing the values of the array's items. The following code snippet initializes item an array's items directly during the declaration.

 

// Initializing jagged arrays

intJaggedArray[0] = new int[2]{2, 12};

intJaggedArray[1] = new int[4]{4, 14, 24, 34};

intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };

 

 

Accessing Jagged Arrays

 

We can access a jagged array's items individually in the following way:


Console.Write(intJaggedArray3[0][0]);

Console.WriteLine(intJaggedArray3[2][5]);

 

We can also loop through all of the items of a jagged array. The Length property of an array helps a lot; it gives us the number of items in an array. The following code snippet loops through all of the items of a jagged array and displays them on the screen.

 

// Loop through all itesm of a jagged array

for (int i = 0; i < intJaggedArray3.Length; i++)

{

    System.Console.Write("Element({0}): ", i);

    for (int j = 0; j < intJaggedArray3[i].Length; j++)

    {

        System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " ");

    }

    System.Console.WriteLine();

}

 

Mixed Arrays

Mixed arrays are a combination of multi-dimension arrays and jagged arrays. The mixed arrays type is removed from .NET 4.0. I have not really seen any use of mixed arrays. You can do anything you want with the help of multi-dimensional and jagged arrays.

 

A Simple Example

Here is a complete example listed in Listing 1 that demonstrates how to declare all kinds of arrays then initialize them and access them.

 

To test this code, create a console application using Visual Studio 2010 or Visual C# Express and copy and paste this code.

 

Console.WriteLine("Single Dimension Array Sample");

// Single dim array

string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" };

// Read array items using foreach loop

foreach (string str in strArray)

{

    Console.WriteLine(str);

}

Console.WriteLine("-----------------------------");

 

Console.WriteLine("Multi-Dimension Array Sample");

string[,] string2DArray = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } };

foreach (string str in string2DArray)

{

    Console.WriteLine(str);

}

Console.WriteLine("-----------------------------");

 

Console.WriteLine("Jagged Array Sample");

int[][] intJaggedArray3 =

{

    new int[] {2,12},

    new int[] {14, 14, 24, 34},

    new int[] {6, 16, 26, 36, 46, 56}

};

// Loop through all itesm of a jagged array

for (int i = 0; i < intJaggedArray3.Length; i++)

{

    Console.Write("Element({0}): ", i);

    for (int j = 0; j < intJaggedArray3[i].Length; j++)

    {

        Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " ");

    }

    Console.WriteLine();

}

Console.WriteLine("-----------------------------");

Listing 1

The output of Listing 1 looks like Figure 1.

arrays1.png
Figure 1

 

Array Class

Array class is the mother of all arrays and provides functionality for creating, manipulating, searching, and sorting arrays in .NET Framework.

 

Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class that means we cannot create an instance of the Array class.

 

Creating an Array

 

Array class provides the CreateInstance method to construct an array. The CreateInstance method takes first parameter as the type of items and second and third parameters are the dimension and their range. Once an array is created, we use SetValue method to add items to an array.

 

The following code snippet creates an array and adds three items to the array. As you can see the type of the array items is string and range is 3. You will get an error message if you try to add 4th item to the array.

 

Array stringArray = Array.CreateInstance(typeof(String), 3);

stringArray.SetValue("Mahesh Chand", 0);

stringArray.SetValue("Raj Kumar", 1);

stringArray.SetValue("Neel Beniwal", 2);

 

Note: Calling SetValue on an existing item of an array overrides the previous item value with the new value.

 

The code snippet in Listing 2 creates a multi-dimensional array.

 

Array intArray3D = Array.CreateInstance(typeof(Int32), 2, 3, 4);

for (int i = intArray3D.GetLowerBound(0); i <= intArray3D.GetUpperBound(0); i++)

    for (int j = intArray3D.GetLowerBound(1); j <= intArray3D.GetUpperBound(1); j++)

        for (int k = intArray3D.GetLowerBound(2); k <= intArray3D.GetUpperBound(2); k++)

        {

            intArray3D.SetValue((i * 100) + (j * 10) + k, i, j, k);

        }

 

foreach (int ival in intArray3D)

{

    Console.WriteLine(ival);

}

Listing 2

Array Properties

 

Table 1 describes Array class properties. 

 

IsFixedSize

Return a value indicating if an array has a fixed size or not.

IsReadOnly

Returns a value indicating if an array is read-only or not.

LongLength

Returns a 64-bit integer that represents total number of items in all the dimensions of an array.

Length

Returns a 32-bit integer that represents the total number of items in all the dimensions of an array.

Rank

Returns the number of dimensions of an array.

 

Table 1


The code snippet in Listing 3 creates an array and uses Array properties to display property values.

 

int[] intArray = new int[3] {0, 1, 2};

if(intArray.IsFixedSize)

{

    Console.WriteLine("Array is fixed size");

    Console.WriteLine("Size :" + intArray.Length.ToString());

    Console.WriteLine("Rank :" + intArray.Rank.ToString());

}

Listing 3

The output of Listing looks like Figure 2.

 

arrays2.png
Figure 2

Searching for an Item in an Array

The BinarySearch static method of Array class can be used to search for an item in an array. This method uses the binary search algorithm to search for an item. The method takes at least two parameters. First parameter is the array in which you would like to search and the second parameter is an object that is the item you are looking for. If an item is found in the array, the method returns the index of that item (based on first item as 0th item). Otherwise method returns a negative value.


Note: You must sort an array before searching. See comments in this article.

Listing 4 uses BinarySearch method to search an array for a string.
 

// Create an array and add 5 items to it

Array stringArray = Array.CreateInstance(typeof(String), 5);

stringArray.SetValue("Mahesh", 0);

stringArray.SetValue("Raj", 1);

stringArray.SetValue("Neel", 2);

stringArray.SetValue("Beniwal", 3);

stringArray.SetValue("Chand", 4);

 

// Find an item

object name = "Neel";

int nameIndex = Array.BinarySearch(stringArray, name);

if (nameIndex >= 0)

    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");

else

    Console.WriteLine("Item not found");

Listing 4

Sorting Items in an Array

The Sort static method of the Array class can be used to sort array items. This method has many overloaded forms. The simplest form takes as a parameter the array you want to sort. Listing 5 uses the Sort method to sort array items. Using the Sort method, you can also sort a partial list of items.

// Create an array and add 5 items to it

Array stringArray = Array.CreateInstance(typeof(String), 5);

stringArray.SetValue("Mahesh", 0);

stringArray.SetValue("Raj", 1);

stringArray.SetValue("Neel", 2);

stringArray.SetValue("Beniwal", 3);

stringArray.SetValue("Chand", 4);

 

// Find an item

object name = "Neel";

int nameIndex = Array.BinarySearch(stringArray, name);

if (nameIndex >= 0)

    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");

else

    Console.WriteLine("Item not found");

 

Console.WriteLine();

 

Console.WriteLine("Original Array");

Console.WriteLine("---------------------");

foreach (string str in stringArray)

{

    Console.WriteLine(str);

}

 

Console.WriteLine();

Console.WriteLine("Sorted Array");

Console.WriteLine("---------------------");

Array.Sort(stringArray);

foreach (string str in stringArray)

{

    Console.WriteLine(str);

}

Listing 5

The output of Listing 5 looks like Figure 3.

arrays3.png
Figure 3

Alternatively the Sort method takes starting index and number of items after that index. The following code snippet sorts 3 items starting at 2nd position.

Array.Sort(stringArray, 2, 3);


The new output looks like Figure 4.

arrays4.png
Figure 4

Getting and Setting Values

The GetValue and SetValue methods of the Array class can be used to get and set values of an array's items. The code listed in Listing 4 creates a 2-dimensional array instance using the CreateInstance method. After that I use the SetValue method to add values to the array. 

In the end, I find number of items in both dimensions and use GetValue method to read values and display on the console. 

Array names = Array.CreateInstance(typeof(String), 2, 4);

names.SetValue("Rosy", 0, 0);

names.SetValue("Amy", 0, 1);

names.SetValue("Peter", 0, 2);

names.SetValue("Albert", 0, 3);

names.SetValue("Mel", 1, 0);

names.SetValue("Mongee", 1, 1);

names.SetValue("Luma", 1, 2);

names.SetValue("Lara", 1, 3);

int items1 = names.GetLength(0);

int items2 = names.GetLength(1);

for (int i = 0; i < items1; i++)

    for (int j = 0; j < items2; j++)

        Console.WriteLine(i.ToString() + "," + j.ToString() + ": " + names.GetValue(i, j));

Listing 6

The output of Listing 6 generates Figure 5.

arrays5.png
Figure 5

Reverse an array items

The Reverse static method of the Array class reverses the order of items in an array. Similar to the Sort method, you can just pass an array as a parameter of the Reverse method. 

Array stringArray = Array.CreateInstance(typeof(String), 5);

stringArray.SetValue("Mahesh", 0);

stringArray.SetValue("Raj", 1);

stringArray.SetValue("Neel", 2);

stringArray.SetValue("Beniwal", 3);

stringArray.SetValue("Chand", 4);

           

Console.WriteLine("Original Array");

Console.WriteLine("---------------------");

foreach (string str in stringArray)

{

    Console.WriteLine(str);

}

 

Console.WriteLine();

Console.WriteLine("Reversed Array");

Console.WriteLine("---------------------");

Array.Reverse(stringArray);

//  Array.Sort(stringArray, 2, 3);

foreach (string str in stringArray)

{

    Console.WriteLine(str);

}

 

Console.WriteLine();

Console.WriteLine("Double Reversed Array");

Console.WriteLine("---------------------");

Array.Reverse(stringArray);

//  Array.Sort(stringArray, 2, 3);

foreach (string str in stringArray)

{

    Console.WriteLine(str);

}

Listing 7

The output of Listing 7 generates Figure 6.

 

arrays6.png
Figure 6

Clear an array items

The Clear static method of the Array class removes all items of an array and sets its length to zero. This method takes three parameters - first an array object, second starting index of the array and third is number of elements. The following code clears two elements from the array starting at index 1 (means second element of the array). 

Array.Clear(stringArray, 1, 2);

Note: Keep in mind, the Clear method does not delete items. Just clear the values of the items.

The code listed in Listing 8 clears two items from the index 1.

Array stringArray = Array.CreateInstance(typeof(String), 5);

stringArray.SetValue("Mahesh", 0);

stringArray.SetValue("Raj", 1);

stringArray.SetValue("Neel", 2);

stringArray.SetValue("Beniwal", 3);

stringArray.SetValue("Chand", 4);

Console.WriteLine("Original Array");

Console.WriteLine("---------------------");

foreach (string str in stringArray)

{

    Console.WriteLine(str);

}

 

Console.WriteLine();

Console.WriteLine("Clear Items");

Console.WriteLine("---------------------");

Array.Clear(stringArray, 1, 2);

 

foreach (string str in stringArray)

{

    Console.WriteLine(str);

}

Listing 8

The output of Listing 8 generates Figure 7. As you can see from Figure 7, the values of two items from the output are missing but actual items are there.

arrays7.png
Figure 7

Get the size of an array

The GetLength method returns the number of items in an array. The GetLowerBound and GetUppperBound methods return the lower and upper bounds of an array respectively. All these three methods take at least a parameter, which is the index of the dimension of an array. The following code snippet uses all three methods. 

Console.WriteLine(stringArray.GetLength(0).ToString());

Console.WriteLine(stringArray.GetLowerBound(0).ToString());

Console.WriteLine(stringArray.GetUpperBound(0).ToString()); 


Copy an array

The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types. 

// Creates and initializes a new Array of type Int32.

Array oddArray = Array.CreateInstance(Type.GetType("System.Int32"), 5);

oddArray.SetValue(1, 0);

oddArray.SetValue(3, 1);

oddArray.SetValue(5, 2);

oddArray.SetValue(7, 3);

oddArray.SetValue(9, 4);

// Creates and initializes a new Array of type Object.

Array objArray = Array.CreateInstance(Type.GetType("System.Object"), 5);

Array.Copy(oddArray, oddArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4);

int items1 = objArray.GetUpperBound(0);

for (int i = 0; i < items1; i++)

    Console.WriteLine(objArray.GetValue(i).ToString());

Listing 9

You can even copy a part of an array to another array by passing the number of items and starting item in the Copy method. The following format copies a range of items from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.

public static void Copy(Array, int, Array, int, int);

Clone an Array

Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

The following code snippet creates a cloned copy of an array of strings.

string[] clonedArray = (string[])stringArray.Clone();

Summary

In this article, you learned basics of arrays and how arrays are handled and used in C#. In the beginning of this article, we discussed different types of arrays such as single dimension, multi dimension, and jagged arrays. After that we discussed the Array class. In the end of this article, we saw how to work with arrays using different methods and properties of the Array class.

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Multidimensional Array by a On August 30, 2006
What is the meaning of the following multidimensinal array declartion :

int [ , , ] arr=new int[4,2,3];

please elaborate.
Reply | Email | Modify 
Re: Multidimensional Array by Jason On April 24, 2007

You are creating an three dimensional array of type int. The array is called arr and the new command creates a new three dimentional array with the dimensions are 4x2x3. When I think of an array, I think of an excel spreadsheet. The a one dimensional array is a row, a two dimensional array is a a row x column, and a three dimensional array is a row x column x page.

Reply | Email | Modify 
Re: Multidimensional Array by mohit On May 10, 2007

hello the declaration u gave:

int[,,] arr=new int[3,2,5]

clearly means we 've declared a 3-dimensional array of int having 3*2*5 no.of elements

i.e.say for example

3 is length

2 is width

5 is height

Reply | Email | Modify 
Re: Multidimensional Array by Unais On February 14, 2008

hi

it is the syntax to declare a multidimensional array.its just like the one we used to declare in c++.

in C++

datatype arrayname[size][size][size];

similarly

int [ , , ] arr=new int[4,2,3];

shows an integer array type in three dimension{int[,,]arr},the comma seperation shows the 3 dimensional or three sets of array.

new int[4,2,3] shows the size of each dimensions or set of values where first one will have 4,second with 2 & 3rd with3,

thats all.hope u understood. still need clarification just mail me in unaisk@yahoo.co.in 

Reply | Email | Modify 
Multi dimensional array by dola On November 22, 2006

Hello,

I read your article on arrays. Nice article

Please can you help with codes on implementing a multidimensional array for  a database that has 5 tables , and each table has 5 attributes and 12 records .

 

How do i populate the tables using the code.

 

Thanks

Reply | Email | Modify 
Re: Multi dimensional array by mohit On May 10, 2007

hello

this problem suggests u need to delare an array of array

i.e.

int[][,] arr=new int[5][5,12]

where 1st array is an array of 5 databases

which in turn is a 2-d array having 5 attributes & 12 records

Reply | Email | Modify 
ARRAY by Tavleen On April 25, 2007
How can we pick words from richtextbox and put them in array of strings? For example if the text of richtextbox is hi , how are you ? then the string array contains hi , how are you ? please reply
Reply | Email | Modify 
Array by Tavleen On April 25, 2007
How can we pick words from richtextbox and put them in array of strings? For example if the text of richtextbox is hi , how are you ? then the string array contains {"hi" , "how" , "are" , "you" , "?" } please reply
Reply | Email | Modify 
multidimensional array(matrix) by abhijeet On May 7, 2007
i want code for following example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Reply | Email | Modify 
DYNAMIC CONTROLS ARAY by LIBERT On May 18, 2007
HI NICE TUTORIAL HELP ALOT I AM NEW AT C# ANDWAS DOING A SOFTWARE THAT REQUIRES THE USER TO ENTER A SERIES OF DATA IN A TABLE (X & Y) AND WAS TRYING TO MAKE A CONTROL THAT A CREATED OF TWO TEXT BOX AND WHEN THE USER HTS THE ADD BUTTON A NEW CONTROL WILL APPEAR UNDER THE FIST ONE
Reply | Email | Modify 
Re: DYNAMIC CONTROLS ARAY by Mahesh On May 19, 2007
You can create a Struct with two members and create an ArrayList object filled with the struct. Alternatively, you may want to use HashTable class.
Reply | Email | Modify 
print the contents? by kiki On August 5, 2007
how can I print the contents of a Multi Dimension Array like string[,] s=new string[20,3]; usining Response.Write() for showing the content?? thank you for your help
Reply | Email | Modify 
Re: print the contents? by Mahesh On August 8, 2007
I guess you want to display contents on a Web page? I would use an HTML table and add TR and TDs to it.
Reply | Email | Modify 
Re: Re: print the contents? by kiki On August 9, 2007
let's say that I want to print the contents in a row, the one under the other, without using td and tr. I try to do it using a for(...) repeating procedure and there are meny errors which I don't understand... can you give me an example? thank you
Reply | Email | Modify 
hello by emani On August 7, 2007
how i can use the sorting (selection & exchanging) for these variables 16 8 12 21 24 11 25 in microsoft visual j++ 6.0 thnk you
Reply | Email | Modify 
unknown size by alex On August 28, 2007
Hi! Is it possible to create an array with dinamyc size? Let say we are reading rows from DB table or lines from a file?
Reply | Email | Modify 
Re: unknown size by Avijit On August 30, 2007

You can better use ArrayList for that purpose. You have to import the System.Collections class

ArrayList al = new ArrayList();
al.Add(1);
al.Add(2);
al.Add(3);

 

Reply | Email | Modify 
Array of object.. by admin On August 31, 2007
nice tutorial but i want array of text box? How to create this in C sharp? please reply
Reply | Email | Modify 
Re: Array of object.. by Mahesh On September 4, 2007
You can user ArrayList class and add TextBox objects to it. When you retrieve textboxes from the ArrayList, you need to convert object to TextBox.
Reply | Email | Modify 
data loading problem by Sathees On September 4, 2007
I have created an array instance as global . I used command click event to load data to this array. Another command click i created to display the content of array. But when I click it says erro messge "Object reference not set to an instance of an object.". But when i try from the previous click function it works. Any help please
Reply | Email | Modify 
data loading problem by Sathees On September 4, 2007
I have created an array instance as global . I used command click event to load data to this array. Another command click i created to display the content of array. But when I click it says erro messge "Object reference not set to an instance of an object.". But when i try from the previous click function it works. Any help please
Reply | Email | Modify 
Re: data loading problem by Mahesh On September 4, 2007
How did you create a global array?
Reply | Email | Modify 
Re: Re: data loading problem by Sathees On September 5, 2007

In the web form after class definition I created it. So that it will be common to all command click events. Following is part of code the code..

 

public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage

{

protected System.Web.UI.MobileControls.Label Label1;

protected System.Web.UI.MobileControls.Label Label2;

protected System.Web.UI.MobileControls.Label Label3;

protected System.Web.UI.MobileControls.TextBox txtcompany;

protected System.Web.UI.MobileControls.TextBox txtarea;

protected System.Web.UI.MobileControls.SelectionList cmbselection;

protected System.Web.UI.MobileControls.Command cmdsearch;

protected System.Data.SqlClient.SqlConnection sqlConnection1;

protected System.Web.UI.MobileControls.Label Company;

protected System.Web.UI.MobileControls.TextView TextView1;

protected System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;

protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;

protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;

protected System.Web.UI.MobileControls.Command cmdhome;

protected System.Web.UI.MobileControls.Label Label4;

protected System.Web.UI.MobileControls.Command Command1;

protected System.Web.UI.MobileControls.Form Form1;

// ArrayList mylist = new ArrayList();

public string [] str = new string[50];

public Array names = Array.CreateInstance( typeof(string),50);

private void cmdsearch_Click(object sender, System.EventArgs e)

{

names.Setvalue(data,j);

}

private void Command1_Click(object sender, System.EventArgs e)

{

this.TextView1.Text = names.GetValue(1).ToString

}

Reply | Email | Modify 
Re: Re: Re: data loading problem by Sathees On September 11, 2007
I did not receive any idea from you,please let me know what can i do...urgent
Reply | Email | Modify 
i have problem in array computation by pieter On October 19, 2007
dear author, my name is pieter...i'm newbie in C-sharp. here is my program list: for ( i = 0; i <= u; i++) { z[i]=a * z[i-1] + c % 16; console.writeline(z[i]); } please check my short list program( because the program doesnt work properly), if don't mind please tell me if i have make a mistake. thank you very much. thank you very much....God Bless... warm greeting from indonesia....
Reply | Email | Modify 
Re: i have problem in array computation by james On January 3, 2008
on the first iteration of loop i=0, therefore (i-1)=-1.  Therefore index of the z array becomes -1 which is most likely the reason behind your error.
Reply | Email | Modify 
Property of an array by Roel On November 8, 2007
Hello, I have a class with an array as one of the fields. I want properties for all the fields, but I don't know how to do this with the array. Example: public class Player { private string name; public Player(string name) { this.name = name } public string Name { get { return name; } } } public class Team { private int number; private Player[] players; public Team(int number) { this.number = number; this.players = new Player[10]; public Player Player { get { ??? } set { ??? } } } } I can get or set a whole array, but how do I do get a specific item of the array? I tried: public Player Player(int i) { get { return players.GetValue(i); } set { players.setValue(value, i); } } but that doesn't work. Can anyone plz help me?
Reply | Email | Modify 
size of array by sanj On February 25, 2008
i want to find ot the size of an array by using while loop as we are doing in C++ like while(str[i] != '\0') {i++;} this code is giving error of array out of bound even though my declared size is much more greater than entered array. plz help me why this is coming. can u tell me how length function is working in C#??????
Reply | Email | Modify 
Re: size of array by Meena On October 15, 2008

int[] intArray;
            intArray = new int[3] { 0, 1, 2 };

            string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
            if (intArray.IsFixedSize)
            {
                Console.WriteLine("Array is fixed size");
                Console.WriteLine("Size :" + intArray.Length.ToString());
            }
            if (names.IsFixedSize)
            {
                Console.WriteLine("Array is varialbe.");
                Console.WriteLine("Size :" + names.Length.ToString());
                Console.WriteLine("Rank :" + names.Rank.ToString());
            }

Reply | Email | Modify 
question by varun On February 28, 2008
how do u compare the equality of 2 diff arrays and also 2 diff strings?
Reply | Email | Modify 
question by varun On February 28, 2008
how do u compare the equality of 2 diff arrays and also 2 diff strings?
Reply | Email | Modify 
C# by Chellammal On March 5, 2008
Toaacept the total number of array elements and values from the user.To arrange elements in ascending order
Reply | Email | Modify 
array by periyasami On October 1, 2008
very nice. Thank u
Reply | Email | Modify 
Logic in c#.net by lakshmi On November 19, 2008
hello any body help me with this i need a logic of if i gave 250.50 in one textbox after clicking the button i should get the twohundread and fifty rupees and fifty paise in textbox2 i need logic please help me
Reply | Email | Modify 
Re: Logic in c#.net by Mahesh On April 6, 2009
Please post your question on forums. See Forums link at the top header.
Reply | Email | Modify 
Arrays by Steven On December 11, 2008
Sorry if this posted twice. I am trying to figure out a way for my program to figure out how many letters where used in what ever word I write in a textbox. For example if I write the word CAB, I want to a messagebox to display or a label to display "You used A 1 time" "You used B 1 time" "You used C 1 time" "You used D 0 times" ..... I don't know how to set up the array to do this. If you could help this very lost student, I would geatly appreciate it!
Reply | Email | Modify 
Re: Arrays by Mahesh On April 6, 2009
Please post your question on forums. See Forums link at the top header.
Reply | Email | Modify 
solve it by smita On January 6, 2009
Explain variable size arrays in c#
Reply | Email | Modify 
Re: solve it by Mahesh On April 6, 2009
Please post your question on forums. See Forums link at the top header.
Reply | Email | Modify 
Where can i get this array class by zain On April 15, 2009
Can someone provide the code for the array class in C?
Reply | Email | Modify 
Re: Where can i get this array class by Mahesh On April 16, 2009
C does not have an Array class. Array class is a part of .NET Framework only.
Reply | Email | Modify 
this article is wrong by ababab On June 17, 2009
This article is WRONG!

In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined. For example, the following like declares a dynamic array of integers.

int [] intArray;


This is just plain wrong.  The above is NOT a declaration for a dynamic array.  The simplest way to get dynamic arrays in C# is with ArrayList.  The Array class is NOT dynamically sizable.

Perhaps the author was confused because Array implements the IList interface.  However, see this:

http://msdn.microsoft.com/en-us/library/system.array.isfixedsize(VS.71).aspx




Reply | Email | Modify 
How initiate an array of objects? by Vadim On June 18, 2009

Hallo,

i have my class and want to create an array of my class' objects. How can i do it? I can't initiate it as
myclass[x] myarray = new myclass(par a, par b)[x];

Thanks

Reply | Email | Modify 
Re: How initiate an array of objects? by danny On August 18, 2009
try like this:


                    MyClass[] myClassArray = new MyClass[100];
                    for(int i = 0; i < myClassArray.Length; i++)
                    {
                        myClassArray[i] = new MyClass(parama, paramb);
                    }



------------------------------
Danny, Los Angeles Locksmith
Reply | Email | Modify 
arrays of object by gaby On July 1, 2009
hello,

I need a little help. I want to set up a array of object, but I can not handle very well.
public class inregistrare
    {
        public static int nr_crt;
        public inregistrare()
        {
            nr_crt++;
        }
        public static string data;
        public static int getnr_crt()
        {
            return nr_crt;
        }

inregistare[] array=new inregistrare[100];

for (int i=0; i<=100; 1++)
{
inregistrare.nr_crt=s.Substring(2,6);
inregistrare.data=...;//nevermind
??array[i]=inregistrare() ????? ;//here I don't know what to do in order to record all the information from inregistrare.nr_crt and inregistrare.data in array[i]
}

I'm just a beginner..

Thank you,
Reply | Email | Modify 
how to read values from array to assign it to list members by lunatic On September 29, 2009

hi  I am a newbie in programming, so not very comfortable with arrays, list and collections stuff, currently working on an application for which I need to read values from an array (the values of array are gathered from an excel data sheet) and assign them to each individual member of the list,

its somewhat like this:

first value of array is assigned to first member of list

second value of array is assigned to second member of list and

so on..

I am having issues building the logic and code to make this work..

Wonder if you can help

Reply | Email | Modify 
Example by sandip On November 11, 2009
Can u give simple example with for loop for 2D array..

Sandip
www.aikadajiba.blogspot.com
Reply | Email | Modify 
Concept regarding TAG by Sachin On November 28, 2009
hello friend i am Sachin,  i am a beginner in .net , please tell me how access the drives present on the computer like c:,d: etc and also the subfolders.Please mail me the answer on my mail id : sgaikwad84@gmail.com
Reply | Email | Modify 
Please help here by Loyiso On February 14, 2010

ABC Cookery class needs a program that will enable them to enter the marks of judges for the class’s  student demos. There are 10 students. Each student has a unique number between 1 and 10(both numbers included). Each student is judged by 3 judges. The marks for the 3 judges are input on Form1. The three marks are loaded into the columns of a 2D array, JudgesMarks. Each row is a student and the columns are the 3 judges’ marks for that student.

Reply | Email | Modify 
thank you by krish On February 28, 2010
this is very useful to me.keep update.


by regards,
  krishna
Reply | Email | Modify 
Closed / Chained Addressing (use array not used linked list) by domin On May 10, 2010
please help me to make console project about "Hashing" Closed / Chained Addressing (use array not used linked list)...thanks
Reply | Email | Modify 
dynamic array by hamza On July 17, 2010
how to print the largest number of a dynamic array
Reply | Email | Modify 
Re: dynamic array by fatkhul On July 27, 2010
Please help me, I want to know result if value errorObjectX is 25 then

w[2]=1-errorObjectX/50;
w[2]=0.5

w[3]=errorObjectX/50;
w[3]=0.5

This is my code:


int errorObjectX=25;

int[] w = new int[5];
            if (errorObjectX <= -100)
            {
               w[0]=1;
            }else if((errorObjectX >-100)&&(errorObjectX <=-50))
            {
                w[0]=-1-errorObjectX/50;
                w[1]=2+errorObjectX/50;
            }else if((errorObjectX>-50)&&(errorObjectX<=0))
            {
                w[1]=-errorObjectX/50;
                w[2]=1+errorObjectX/50;
            }else if ((errorObjectX>0)&&(errorObjectX<=50))
            {
                w[2]=1-errorObjectX/50;
                w[3]=errorObjectX/50;
            }else if ((errorObjectX>50)&&(errorObjectX<=100))
            {
                w[3]=2-errorObjectX/50;
                w[4]=-1+errorObjectX/50;
            }else
            {
                w[4]=1;
            }

          foreach (int array in w)
            {
                Console.WriteLine(array);
            }
            Console.Read();
Reply | Email | Modify 
What about this line by John On October 25, 2010
Hi,

Great script, I need to know what is the meaning of this line:
int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} };

Thanks,
John Wolcot
Locksmith Austin

Reply | Email | Modify 
Re: What about this line by Mahesh On January 13, 2011
A dynamic (no size limit) jagged array of two arrays. Each item of this array can have two children arrays. First child array can have 3 integers and second child array can have 5 integers.
Reply | Email | Modify 
a by rika On December 25, 2010
i want to make a database with array which is the output is a table that all my inputed will view in the table
Reply | Email | Modify 
Re: a by Mahesh On January 13, 2011
What exactly are you trying to do? You are probably better of using collection classes to store your collections and serialize with database.
Reply | Email | Modify 
Dynamic arrays by Sam On January 13, 2011
This is an excellent article about arrays and I am sure it has helped many people. I apologize, however, for having to say this, but I agree with ababab on June 17, 2009. I would not be harsh as in that comment, but I agree that the Array class does not support dynamic arrays. If it does, I am very interrested in seeing examples of that. Also, what happens when an unsorted array is searched using BinarySearch? Is the array automatically sorted first? I assume not, so I assume it would help to state explicitly that an array must be sorted for the BinarySearch to work. Also note that the example of sorting an array is not an example of sorting an array.
Reply | Email | Modify 
Re: Dynamic arrays by Mahesh On January 13, 2011
Sam, I think you have not looked at Array class. It support generics and you can do anything you want with it now. I just did not get a chance to cover all methods and properties. Also, you can apply sorting on an array in both ways with the help of Reverse method. Why does it matter what method array uses to sort as long as my items are sorted. When you search, array physically is not sorted but I am sure it is sorted in the framework (memory) otherwise how would binary search would work? Searching just give you the index of an item. Does not changes positions of the items. Cheers!
Reply | Email | Modify 
Re: Re: Dynamic arrays by Sam On January 13, 2011
See: http://msdn.microsoft.com/en-us/library/y15ef976.aspx It says "array must be sorted before calling this method".
Reply | Email | Modify 
Re: Re: Re: Dynamic arrays by Mahesh On January 13, 2011
OK got it. I missed that part. Actually, I searched without sorting and it gave me the right index.
Reply | Email | Modify 
Hi sir by ashok On February 16, 2011
Good job..
Reply | Email | Modify 
array , try catch method by gishnu On May 20, 2011
can i use try catch when i get values for user for an array, is that necessary,
Reply | Email | Modify 
String Arrays by A On June 5, 2011
So you show how to initiate arrays with names you already know. How do you get user input names INTO an array? string[] names = new string [100] So I don't know the names, I just know you can enter up to 100 strings. Now how do you get the names you enter from a method INTO THE STUPID array? You don't show that at all, which makes this article useless for anything practical other than displaying a set of pre-defined names.
Reply | Email | Modify 
Re: String Arrays by Jared On August 24, 2011
Wow! Calling an article useless is a little harsh, especially when the answer is in the article, you just didn't see it. If you have an array: string[] names = new string[100]; The article clearly states that you can assign a value as follows: names[0] = "John"; names[1] = "Mark"; You could even do something basic like check if the item in the array is already populated and populate the first empty instance: string[] names = new string[100]; public int AddName(string inName) { for (int id = 0; i < names.Length; id++) { if (String.IsNullOrWhiteSpace(names[id])) { names[id] = inName; return id; } } } Hope that helps, Jared <a href="http://www.rhyous.com/2011/08/24/arrays-in-c-sharp/">Arrays in C#</a>
Reply | Email | Modify 
Very Clear understanding!! by Vijay On August 23, 2011
Very good Article.
Reply | Email | Modify 
qustion regarding array by pritam On December 13, 2011
when we create an single dimmensional array ,in that we want to find perfect square number.then how we will find it??
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.