Working with Arrays in C#

By Anand Narayanaswamy

In this article, we will take a close look at working with arrays. We will also examine various access modifiers and how to work with command line arguments in C#.

Arrays give us a list of items of similar data types. For example, to store the names of students, you can use an array of type string; to store their ages, an integer type can be used.

In C#, arrays are derived from the System.Array class. There are lot of properties and methods in this class; we can manipulate these for our programming tasks. Arrays in C# are declared in the same fashion as in Java or C++; they can be either single- or multidimensional. The following code declares a single dimensional array of type integer and with a dimension of 10. Dimension indicates the number of array elements.

Listing 1

int[] x = new int[10]

Arrays can also be declared as in Listing 2:

Listing 2

int[] x = {2,3,4,5,6}

The preceding statement stores four integer values; the index position for the first element will be always zero. Listing 3 illustrates how to print the values in an array.

Listing 3

using System;
class PrintArray
{
  public static void Main(String[] args)
  {

    int[] x = {10,20,30,40,50};
    for(int i = 0; i<=4;i++)
    {
      Console.WriteLine(x[i]);
    }
  }
}

You also can use the Length property of the System.Array class to determine the dimensions of an array. Listing 4 makes use of this handy property.

Listing 4

using System;
class Printlength
{
  public static void Main(String[] args)
  {

    int[] x = {10,20,30,40,50};
    for(int i = 0; i<x.Length;i++)
    {
      Console.WriteLine(x[i]);
    }
  }
}

C# also supports multidimensional arrays. They can be represented as shown in Listing 5:

Listing 5

// Three-dimensional array (Count the number of commas and
// add 1 to the result)
int[,,] x

// Two-dimensional array
int[,] y

Listing 6 explains the usage of multidimensional arrays:

Listing 6

using System;
class Multi
{
  public static void Main()
  {
    int[,]x;
    x = new int[4,4];
    x[0,0] = 1;
    x[1,1] = 1;
    x[2,2] = 1;
    x[3,3] = 1;
    Console.WriteLine(x[0,0] +" " +x[0,1] + " " +x[0,2] + " "+x[0,3]);
    Console.WriteLine(x[1,0] +" " +x[1,1] + " " +x[1,2] + " "+x[1,3]);
    Console.WriteLine(x[2,0] +" " +x[2,1] + " " +x[2,2] + " "+x[2,3]);
    Console.WriteLine(x[3,0] +" " +x[3,1] + " " +x[3,2] + " "+x[3,3]);
  }
}

Multidimensional arrays are also called rectangular arrays because each row will be the same length. C# also supports yet another type of array, called the jagged array. It's termed an array of arrays. In the case of a jagged array, each row will be a different length. It can be represented as shown in Listing 7:

Listing 7

// Jagged Array int [][] x = new int[2][];

Listing 8 illustrates the usage of a jagged array:

Listing 8

using System;

class Jagged
{

  int [][] x = new int[2][];

  void set()
  {
    x[0] = new int[2];
    x[1] = new int[2];

    x[0][0] = 1;
    x[0][1] = 2;
  }

  void show()
  {
    for(int i = 0; i<2;i++)
    {
       for(int j = 0;j<2;j++) 
       {
         Console.WriteLine(x[i][j]);
       }
    }
  }

  public static void Main() 
  {
    Jagged j = new Jagged();
    j.set();
    j.show();
  }
}

You can programmatically determine the dimension of an array by using the Array.Rank property, as shown in Listing 9:

Listing 9

using System;
class Ranks
{

  int[] SD;
  int[,] MD;
  int[,,] TD;

  Ranks()
  {

    SD = new int[10];
    MD = new int[10,20];
    TD = new int[10,20,30];

  }

  void Display()
  {
    Console.WriteLine("SD = {0}",SD.Rank);
    Console.WriteLine("MD = {0}",MD.Rank);
    Console.WriteLine("TD = {0}",TD.Rank);
  }

  public static void Main(string[] args)
  {
    Ranks r = new Ranks();
    r.Display();
  }
}

Access Modifiers

Access modifiers determine the scope of visibility for variables and methods. There are four types of modifiers in C#: Public, Protected, Private, and Internal. For example, a variable declared as private in a super class cannot be called in a sub class. It should be declared as either public or protected. Let's examine each of these in detail.

  1. Public members are accessible from outside the class definition.
  2. Protected members are not visible outside the class and can be accessed only by derived or sub classes.
  3. Private member's scope is limited to the defined class. Derived classes or any other classes cannot access these members.
  4. Internal members are visible only within the current compilation unit.

Working with Command Line Arguments

Normally, we pass values and input information by using the keyboard. This functionality can be achieved easily by using C++ and making use of the cin keyword. But, there is no such keyword in C#. You have to call some advanced namespaces and classes, which we will examine later. However, this functionality is achievable by passing command line arguments. Listing 10 examines this concept:

Listing 10

using System;
class CommandLine
{
  public static void Main(string[] args)
  {
    foreach(string arg in args)
    {
      Console.WriteLine("Argument :{0}",arg);

    }
  }
}

About the Author

Anand Narayanaswamy works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials. He can be reached at anand@learnxpress.com.

# # #



About the Author

Anand Narayanaswamy

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Comments

  • program

    Posted by gerald on 01/15/2013 01:31am

    please help me make me a program that 3 players using arrays input total score of each player per quarter of the game. output the player name and all 4 score per quarter and the average score of the player

    Reply
  • good article

    Posted by John on 12/22/2012 08:58pm

    http://www.microsoft-csharp-tutorials.com/post/2012/12/22/Arrays-in-C

    Reply
  • Another Nonsense!

    Posted by Gasha on 03/21/2011 05:40am

    What is the usage of the example intended to highlight the difference
    between Rectangular and Jagged arrays (Listing 8 above) as you've
    fixed the length of both the dimensions at 2? (again a rectangular array)
    A better example may be as follows:
    
    using System;
    class Jagged {
    	int[][] x = new int[2][];
    
    	void setValues() {
    		x[0] = new int[2];
    		x[1] = new int[3];
    
    		x[0][0] = 1;
    		x[0][1] = 2; // 1st row ends here
    		x[1][0] = 3;
    		x[1][1] = 4;
    		x[1][2] = 5; // 2nd row ends here
    	}
    
    	void displayValues() {
    		for (int i = 0; i < x.Length; i++) {
    			for (int j = 0; j < x[i].Length; j++) {
    				Console.Write(x[i][j] + "\t");
    			}
    			Console.WriteLine(); // to move cursor to next line
    		}
    	}
    
    	public static void Main() {
    		Jagged jagged = new Jagged();
    		jagged.setValues();
    		jagged.displayValues();
    		Console.ReadKey();
    	}
    }

    Reply
  • Free C# e-books

    Posted by Mr_Code28 on 07/11/2009 12:07am

    please somebody wants to share e-book in C#

    Reply
  • under standing Array

    Posted by vikas_2683 on 12/27/2007 05:05am

    so sopporting

    Reply
  • Listing 2

    Posted by Legacy on 10/06/2002 12:00am

    Originally posted by: John P

    In Listing 2 you have:

    "int[] x = {2,3,4,5,6}

    The preceding statement stores four integer values; the index position for the first element will be always zero."

    Actually, five integer values are stored in that array. The index, however, has a valid range of zero to four.

    John

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds