Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
10.7%
c#.net


 by Lakpriya Kottahachchi

Welcome to the C#.NET section of the Digit magazine. During the last session we had a closer look at some of the most important object oriented concepts going around. Inheritance, Encapsulation and Polymorphism are some of them. There we created some C# code which would implement the above concepts and illustrated them one by one. Furthermore we emphasized the value of those concepts when we are doing programming. Hence having a good idea about the use of object oriented concepts would be really advantageous.

Thus far we discussed some important C# theories as well as some valuable object oriented concepts. From now on will dive into some tough programming concepts in C#, these are very important and would help to improve your knowledge in the subject by quite a lot. In the next few articles we would discuss on Arrays, Collection types and Iterators in C#. NET as well as Exception handling as well. We would spend some time on these as they are very important programming techniques. In this week we will start to work on Arrays, and gradually we would move into more advance data collections.


Arrays in C#

What are arrays..?

An array is a data structure that contains several variables of the same type. Arrays are declared with a type. That type could be an Integer, String, and Float… or can even be another object.

An array has the following properties:

  •    An array can be Single-Dimensional, Multidimensional or Jagged.

  •   The default value of numeric array elements are set to zero, and reference elements are set to null.

  •    A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

  •    Arrays are zero indexed: an array with n elements is indexed from 0 to n-1

  •   Array elements can be of any type, including an array type.

  •   Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable, you can use foreach iteration on all arrays in C#.


An Array can be defined as,

int [] intArray;
The following code declares an array, which can store 5 items starting from index 0 to 4.

int [] intArray;
intArray = new int[5];
The following code declares an array that can store 100 items starting from index 0 to 99.

int [] intArray;
intArray = new int[100];

P.N: In a array we should explicitly give the length or the size of the array, if not we have to declare the elements of the array with in “{}” (curly brackets). If you don’t follow these practices the complier will issue an error.

string[] strArray = {"Ronnie", "Jack", "Lori", "Max", "Tricky"};


Single Dimensional 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 in a row starting from 0 to the size of array -1.

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

int [] intArray;
intArray = new int[5];

Multidimensional Arrays

A multidimensional array is an array with more than one dimension. A multi dimension array is declared as following:
string[,] strArray;

After declaring an array, you can specify the size of array dimensions if you want a fixed size array or dynamic arrays. For example, the following code two examples create 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 respectively.


int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] names = new string[2, 2] { {"Rosy","Amy"}, {"Peter","Albert"} };

Jagged Arrays


Jagged arrays are often called array of arrays. An element of a jagged array itself is an array. For example, you can define an array of names of students of a class where a name itself can be an array of three strings - first name, middle name and last name. Another example of jagged arrays is an array of integers containing another array of integers. For example,


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


Again, you can specify the size when you call the new operator.

Mixed Arrays

Mixed arrays are a combination of multi-dimension arrays and jagged arrays. Multi-dimension arrays are also called as rectangular arrays.

P.N:  In most cases use of single dimensional arrays is more frequent, it is seldom that you find other type of arrays which we mentioned above would be used in conventional programming, unless it is a game or some kind. But it is good know that such kind arrays types also exists.

  • In an array it is necessary that you should access every single array element in order to retrieve data from them.
  • To do that we need to use a ‘for’ loop to go through the entire array. The number of times the ‘for’ loop would loop would depend on the length of the array. This is also possible in C#.
  • But the specialty in C# in that it allows a keyword called ‘foreach’ to go through the array and access each and every element.

This sample code illustrates it,

int[] numArray = {1, 2, 5, 6, 10, 14, 115};
foreach (int num in numArray)
{
System.Console.WriteLine(num.ToString());
}

To get a broader idea about what we discussed so far, let’s look at an example



                                                                  

Figure 1: Output of the code sample

static void Main(string[] args)

        {

            int[] numbers = new int[3];

            // adding elements to the array

            numbers[0] = 1;

            numbers[1] = 3;

            numbers[2] = 5;

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

            foreach (int i in numbers)

            {

                Console.WriteLine(i);

            }

            Console.WriteLine("===============");

            Console.WriteLine();

            // Array declaration with elements

            string[] names = {"Saman","Nadun", "Kasun", "Isuru" };

            foreach (string name in names)

            {

                Console.WriteLine(name.ToString());

            }

            Console.WriteLine("===============");

            Console.WriteLine();

            // Two dimensional array

            string[,] strArray = new string[,]

            {

            {"Rosy","Amy"},

            {"Peter","Albert"}

            };

            foreach (string str in strArray)

            {

                Console.WriteLine(str);

            }

            Console.ReadLine();

        }

Figure 2: Code sample for the implementation of arrays


  •       Thus far we declared arrays using normal coding, but in C# there is a inbuilt class specifically designed to be used in matters related to handling on arrays.

  •    The Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class but it provides “CreateInstance” method to construct an array. The Array class provides methods for creating, manipulating, searching, and sorting arrays.

The below table contains some properties of the array class:


Figure 3: The System.Array Class Properties

In the next article we would discuss more about this array class and would inspect some code associated it to it. Furthermore we would get to know about some of the more complex data collectors as well.

 Previous Article

Share/Save
No votes yet

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options