Arrays, declaration and default initialization of arrays in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 6665 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.

Introduction

So far, we have seen Chars and Strings in C#. Let's discuss about arrays and creating arrays in this article.

Objective

The main objective of this article is to learn arrays of both Chars and Strings and also default element initialization of arrays in C# programming.

Array

Array is a fixed number of variables of particular type which are called as Array Elements. These elements provides high efficient access and always stored in a contiguous block of memory.

Declaration of Array:
Array's are denoted square braces after the type of the element and declared as below,
char[] array = new array[4]  // This is the array with 4 elements
We can access the particular element of an array by using the index of an array. 
'Indexes' of array starts at 0
array[0] = 'a1';
array[1] = 'a2';
array[2] = 'a3';
array[3] = 'a4';

Console.WriteLine(array[2])  // prints 'a3'

Methods of declarations:
Let's have a simple example code with clear explanation,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            char[] Alphabets = new char[4];

            Alphabets[0] = 'A';
            Alphabets[1] = 'B';
            Alphabets[2] = 'C';
            Alphabets[3] = 'D';

            Console.WriteLine(Alphabets[1]);    // Prints B as index starts with 0
        }
    }
}
The above code illustrates an array of 'Alphabets' with four elements. This prints 'B' in the Console as its index is 1.


Other ways of declaring an array are,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            char[] Alphabets = new char[4] { 'A', 'B', 'C', 'D' };

            Console.WriteLine(Alphabets[1]);            // Prints B as its index is 1

            char[] Numbers = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            Console.WriteLine(Numbers[5]);              // Prints 6 as its index is 5
        }
    }
}
In the above code we have two more methods of array declarations which performs the same functionality.


Using for loop:
We can use for loop to iterate through each element in the array.
Ex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            char[] Alphabets = new char[4] { 'A', 'B', 'C', 'D' };

            for (int i = 0; i < Alphabets.Length; i++)
            Console.WriteLine(Alphabets[i]);        // Prints A B C D vertically as we used WriteLine
        }
    }
}
In the above code, we are using for loop which iterates the entire Alphabets array. This will prints all the array elements in the Console like below,


And if we use Console.Write instead of Console.WriteLine,


Arrays with Strings

We can also create an array with strings as we did for the char's above. Observe the below example of strings,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            string[] fruits = new string[5];

            fruits[0] = "Apple";
            fruits[1] = "Banana";
            fruits[2] = "Mango";
            fruits[3] = "Orange";
            fruits[4] = "Pineapple";

            Console.WriteLine(fruits[2]);     // Prints Mango
            Console.WriteLine(fruits[0]);     // Prints Apple
        }
    }
}
In the above code, we have created an array of fruits with 5 elements (fruit names).  
Output of the above code will be,


Other ways of declaring strings are,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            string[] fruits = new string[5] { "Apple", "Banana", "Mango", "Orange", "Pineapple" };

            Console.WriteLine(fruits[3]);     // Prints Orange
            Console.WriteLine(fruits[2]);     // Prints Mango

            string[] flowers = { "Rose", "Jasmine", "Lily", "Sunflower" };

            Console.WriteLine(flowers[0]);    // Prints Rose
            Console.WriteLine(flowers[2]);    // Prints Lily
        }
    }
}
Similar to char's, the other ways of declaring string array's are shown in the above code.
Output of the above example code is,


Default Element Initialization

Initially an array initializes its elements with default values. Default value means the result of a bitwise zeroing of memory. 
Let's consider an example below,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            int[] a = new int[100];

            Console.WriteLine(a[23]);  // Prints 0 as a default value
            Console.WriteLine(a[52]);  // Prints 0 as a default value
        }
    }
}
In the above example code, we have created an array with 100 elements which doesn't has any values. It prints 0 in the Console as the default value for each element will be 0.


Value Types:
We have already discussed about value types in the previous chapters. When the array element type is a value type, each element value is allocated as part of an array.
Ex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        public struct Array
        {
            public int A, B;
        }
        static void Main()
        {
            Array[] a = new Array[100];
            int c = a[50].A;

            Console.WriteLine(c);  // Prints 0
        }
    }
}
Above code prints 0 in the Console as following,


Reference Types:
We have already seen about reference types in previous chapters. Creating an array with reference type would have merely multiple null references.
Ex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        public class Array
        {
            public int A, B;
        }
        static void Main()
        {
            Array[] a = new Array[100];
            int c = a[50].A;

            Console.WriteLine(c);  //  Null reference Exception occurs
        }
    }
}
This code will throw a NullReferenceException in the Console as following,


To avoid this error, we have to instantiate all the Array elements explicitly after instantiating the array. We can use for loop to do that. Example,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        public class Array
        {
            public int A, B;
        }
        static void Main()
        {
            Array[] a = new Array[10];

            for (int i = 0; i < a.Length; i++) // Iterates i from 0 to 9
            {
                a[i] = new Array();            // Sets array element i with the new point (array)

                Console.WriteLine(a);          // Prints 10 values of array elements
            }
        }
    }
}
In the above code, for loop iterates all the array elements from 0 to 9 as length of the array mentioned is 10.

Note: Please read the comments in the code.

Now the output will shows the 10 array elements as following,


Conclusion

In this article, we have studied creating arrays of chars and strings and also default element initialization of arrays in C#. Hope you understand. 

Thanks for reading.

Regards,
Krishna.
Recommendation
Read Multidimensional Arrays in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)