Monday 26 January 2015

Arrays in C-sharp

Contents:


  • Introduction
  • Syntax
  • Defining Array
  • Initializing Array
  • Accessing Array
  • Types of Array
  • Array Class
  • Array Properties
  • Array class Methods
  • Getting and Setting value in array



Introduction :


  • An Array is the collection of similar data type.
  • An array is a special variable which is use to perform operation more than one value of same type at a time.
  • An array starts at zero means the first item of an array is at 0th position.
  • Position of last item of an array will be total no. of item -1.
  • Array can be declared as fixed length and dynamic.
  • Array cannot grow in size once initialized have to rely on integral indices to store or retrieve items from the array.


Syntax :

           int[] arr ;
           arr = new int[5];

or

          int[] arr = new int[5];


Defining Arrays of different types :

double[] douarr = new double[10];
char[] chararr = new char[10];
bool[] boolarr = newbool[2];
string[] strarr = new string[6];

Initializing Arrays :

Initializing a fixed array
                       int[] staticarr = new int[3] {1,3,5}

Initializing a fixed array one item at a time
                      staticarr[0]  = 1;
                      staticarr[1]  = 1;
                      staticarr[2]  = 1;

Initializing a dynamic Array
                     string[] arr = new string[] {"John","Samson","Michael"};

Accessing Array :

Initializing fixed Array one at a time

                     Int[] staticarr = new Int[3];
                             staticarr[0] = 1;
                             staticarr[1] = 2;
                             staticarr[3] = 3;

 Read Array item one by one

                     Console.WriteLine(staticarr[0]);
                     Console.WriteLine(staticarr[1]);
                     Console.WriteLine(staticarr[2]);

Accessing an array using foreach loop

                     int[] arr = new int[]{1,2,3,4,5};
                     foreach(int i in arr)
                     {
                             Console.WriteLine(i);
                      }

Types of Array :

*Single-dimensional Array
*Multi-Dimensional Array
*Jagged Array


Single dimensional Arrays

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

Multi dimensional Arrays :  Array with more than one dimensions

string[,] multiDstring = new string[2,2]{{"john", "Samson"},{"Hardik","ramson"}};

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

int[,] number = new int[2,2];
number[0,0] = 1;
number[0,1] = 8;
number[1,0] = 9;
number[1,1] = 15;

Accessing multi-dimensional arrays

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

Jagged Arrays

*Array of arrays
*Element of jagged arrays are the other arrays.

Declaration of jagged Arrays

int[][] intJArr = new int[3][];
string[][] sJArr = new string[2][];

int JArr[0] = new int[2] {2,14};
int JArr[1] = new int[4] {2,6,16,14};
int JArr[2] = new int[3] {2,1,87};

Accessing jagged Array  : we can access a jagged item

Console.Write(JArr[0][0]);
Console.WriteLine(JArr[1][3]);

Accessing of jagged array using Loop :

for(int i = 0; i <JArrLength; i++)
{
      Console.Write("Element [{0}] : ", i)
       for(int j = 0; j <JArr; j++)
       {
                Console.Write("{0}{1}", JArr[i][j], j == (JArr[i].Length - 1) ? "" : " " ); //**
        }
}

**this is conditional statement in which  JArr[i].Length – 1 getting an array length-1 if its try it print nothing also its false it will print nothing.
This is what this line is doing.

Note:-The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

condition ? first_expression : second_expression;

However, the high-level ternary statement is useful because it allows you to condense multiple if-statements and reduce nesting. It does not actually eliminate branching. It simplifies the high-level representation of the branching.

Example:

C# program that uses ternary operator
 
using System;
 
class Program
{
    static void Main()
    {
        //
        // If the expression is true, set value to 1.
        // Otherwise, set value to -1.
        //
        int value = 100.ToString() == "100" ? 1 : -1;
 
        Console.WriteLine(value);
    }
}
 
Output : 1


Array Class :

Mother of all array and provide functionality for creating, manipulating, searching and sorting arrays. Array class, defined in the system namespace, is the base class for array in c-sharp. Array class is the abstract base class that means we cannot create the instance of array class.

Creating an Array :

        Array class provide the CreateInstance method to construct an array. The CreateInstance method take first parameter as the type of item and second and third are the dimensions of there range.

Once array is created we use SetValue to add and modify item of an array.

Array SArray = CreateInstance(typeof(String),3);
SArray.SetValue = ("Ravi rampal",0);   //old value
SArray.SetValue = ("Johny Kennedy",1);
SArray.SetValue = ("Sachin tendulkar",0);    // modified value 
SArray.SetValue = ("Nick floyed",2);

Note: - always print modified value in the above statements Sachin Tendulkar is print in console instead of  Ravi rampal.

Array properties :


  • IsFixedSize : Return a value indicating if an array has fixed size or not.
  • IsReadOnly : Return a value if an array read only or not.
  • LongLength: Return 64 bit integer represent total items in array.
  • Length: Return 32 bit integer represent total items in array.
  • Rank: Return no. of dimensions of an array.
  • SyncRoot: Return an object that can be used to synchcronize access  to the array.




Array Class Method :


  • BinarySearch: This method searches one-dimensions sorted array for a value, using a binary search algorithm.
  • Clear: This method removes all the items of an array and set a range of items in the array to 0.
  • Copy: This Method copy a section of one array to another array and perform typecasting and boxing as required.
  • CopyTo: Copies all the item of current one-dimensional array to the specified one-dimensional array starting at the specified destination index.
  • CreateInstance: Initialize a new instance of an array class or construct a new array.
  • GetEnumerator: Returns a IEnumerators for the array.
  • GetLength: Returns the no. of items in an array.
  • GetLowerBound: Returns a Lower Bound of an array.
  • GetUpperBound: Returns Upper Bounds Of an array.
  • GetValue: Returns the value of specified Items in an array.
  • IndexOf: This method returns the first occurrence of a value in one-dimensional array or in a portion of the array.
  • Initialize: Initialize every item of the value type array by calling the default constructor of the value type.
  • LastIndexOf: Return the index of last occurrence of a value in array or in a portion of the array.
  • Reverse: This method reverse the order of items in the one-dimensional array or in a portion of array.
  • SetValue: This method set the specified items in the current array to the specified value.
  • Sort: Sort the items in the one-dimensional array.


Getting and setting value in array :

GetValue returns a value from index of an array items at a specific index.

Setvalue set and modified value of an array items at a specified index.

Array names = Array.CreateInstance(typedef(string) 2,2)

names.SetValue("Rosy",0,0);
names.SetValue("Amy",0,1);
names.SetValue("Peter",1,0);
names.SetValue("John",1,1);