Lesson 5: Arrays, Collections, Generics and Namespaces

array

image credit:codeproject.com



 


Collections

We have used a variable to store reference to a single value. What should we do if we need to reference multiple values in a single variable?

The answer to this question lies in the introduction of Collections.First we will look at the array object in C#

Array

Array is the storage of the items of same type.Each item in an array is referenced by its index number.The index number denotes the location of an object inside an array.It always starts with 0 .
In order to use an array in our program,we have to use System.Collections class.The arrays may be of integer,character,double,object,string etc

How to initialize an array?

There are several techniques used to initialize an array.Such as:

int[] Myarray = new int[10];

[ ] denotes index notation necessary for array,new keyword creates a new instance of an array,MyArray is the name of the array.10 is the size of an array.

Other styles for array initialization are as follows:

//Elements are initialize immediately
int[] MyArray = new int[] {200,400 ,600 ,800 ,1000 };

In the above line,we haven’t mentioned the size of an array but the compiler will understand that the size of an array is 5 by counting its number of elements

Array using objects and accessing them

using System;
using System.Collections;

class Program
{

static void Main()
{

object[] ObjectArray = new object[3] { “Batman”, “Spiderman”, “Superman” };

/*Accessing the first value at zeroeth index of an array*/

Console.WriteLine(“Accessing first valuen”);
Console.WriteLine(“First Value is at index[0]={0}nn”, ObjectArray[0]);

/* Accessing all the values through for loop */

Console.WriteLine(“Using for loopn”);
for (int i = 0; i < ObjectArray.Length; i++)
{

Console.WriteLine(“Value at index{0} is {1}”, i, ObjectArray[i]);

}

/* Accessing array values with foreach loop */
Console.WriteLine(“nnUsing foreach loopn”);

foreach (object o in ObjectArray)
{

Console.WriteLine(“SuperHero={0}”,o);

}

/*Accessi array through While loop */
int count = 0;
Console.WriteLine(“nnUsing While Loopn”);

while (count<ObjectArray.Length)
{

Console.WriteLine(“Value at index{0} is {1}”, count, ObjectArray[count]);
count++;

}

}
}

Output

 

Multi-dimensional array

Multi-dimensional arrays can be consider as a matrix used in Mathematics.The elements are stored in rows an column-wise fashion.Let’s take an example of using 2D array and accessing its element

Example

using System;
using System.Collections;

class Program
{

static void Main()
{

/* The outer brackets represent a row

* So,the element ‘Batman’ is the zeroeth element of the zeroeth row.
* which can be read as the first element of the first row
* We can access this as stringArray[0][0]
* [3,2] denotes two rows and two elements for each row
*/

string[,] My2D = new string[3, 2] { { “superman”, “spiderman” }, { “batman”, “krrish” },
{ “hulk”, “magnificientseven” } };

/*Getting the value krrish */

Console.WriteLine(“n Getting the value ‘krrish'”);

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

Console.WriteLine(“n Getting all the values with nested for loops n”);

for (int i = 0; i < My2D.GetLength(0); i++)
{

for(int j=0;j<My2D.GetLength(1);j++)
{

Console.WriteLine(My2D[i, j]);

}

}

/* Getting all the values through foreach*/

Console.WriteLine(“n Getting all the values with for each”);

foreach(string s in My2D)

{

Console.WriteLine(s);

}
}

}

Output

 

The three dimensional array is denoted as:

int[, ,] My3D = new int[,,] { { { 100, 102, 104 }, { 106, 108, 110 } }, { { 112,114, 116 }, { 118, 120, 122 } } };

To access 120,we write

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

Jagged Array

An array of arrays is known as jagged array.It is single dimensional and the arrays which it contains as its elements need not be of same size

Example

using System;
using System.Collections;

class Program
{

static void Main()
{

/*Declaring a jagged array*/
char[][] jagged = new char[4][];

/*Iniitializing jagged array with different sizes arrays*/

jagged[0] = new char[2] { ‘a’, ‘b’ };
jagged[1] = new char[3] { ‘c’, ‘d’, ‘e’ };
jagged[2] = new char[7] { ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’ };
jagged[3] = new char[4] { ‘m’, ‘n’, ‘o’, ‘p’ };

/*Looping through jagged array.
Since jagged array is single dimensional.We use
* single for loop
*/

for(int i=0;i<jagged.GetLength(0);i++)
{

Console.WriteLine(jagged[i]);

}

}

}

Output

Built in methods for array operation

Sort(),GetLength(),Type() etc are the methods which I expect from you to look for.

Array of objects

Arrays are not only used with simple types such as int,char,string,objects.But they can be applied to real object types such as classes

Example

using System;
using System.Collections;

namespace CDCollection
{

class Krrish3
{
private double _boxoffice;
private string _hero;
private DateTime _releasedate;
private string _category;

public double BoxOffice
{
get
{

return this._boxoffice;

}

set

{

this._boxoffice = value;

}
}

public string Hero
{
get

{
return this._hero;

}

set
{
this._hero = value;

}
}

public string Category
{
get
{
return this._category;

}

set
{
this._category = value;

}
}

public DateTime ReleaseDate
{
get

{
return this._releasedate;

}
set
{
this._releasedate = value;

}
}
}

class Program
{
static void Main(string[] args)
{
/*Array of class Krrish3*/
Krrish3[] krrish3 = new Krrish3[20];

for (int i = 0; i < 20; i++)
{
krrish3[i] = new Krrish3();
}

// boxoffice = 300.0;
//_hero = “Hrithik Roshan”;
//_releasedate = DateTime.Now.AddDays(-10);
//_category = “Blockbuster”;

krrish3[0].Hero = “Hrithik Roshan”;

DateTime dt = new DateTime();
krrish3[0].ReleaseDate = Convert.ToDateTime(“11/01/2013”);
krrish3[0].BoxOffice = 300;
krrish3[0].Category = “Blockbuster”;

Console.WriteLine(“Krrish3nn”);
Console.WriteLine(“Hero:{0}”,krrish3[0].Hero);
Console.WriteLine(“nRelease Date:{0}”, krrish3[0].ReleaseDate);
Console.WriteLine(“nBox office:{0}$”, krrish3[0].BoxOffice);
Console.WriteLine(“nStatus:{0}”, krrish3[0].Category);

}
}
}

Output

 

Array as Argument:

using System;
using System.Collections;

class Program
{

public static void ShowMe(int[] argArray)
{

foreach(int i in argArray)

{

Console.WriteLine(i);

}

}

static void Main()
{

int[] argArray = { 12, 13, 14, 15, 16 };
ShowMe(argArray);
}
}

Output

12
13
14
15
16
ArrayList

ArrayList is another way to store any value or reference without modification to their types. It stores anything in the form of object,hence we don’t have to define the type of the elements

Examples

Example 1

using System;
using System.Collections;

namespace CDCollection
{

class Krrish3
{
private double _boxoffice;
private string _hero;
private DateTime _releasedate;
private string _category;

public double BoxOffice
{
get
{

return this._boxoffice;

}

set

{

this._boxoffice = value;

}
}

public string Hero
{
get

{
return this._hero;

}

set
{
this._hero = value;

}
}

public string Category
{
get
{
return this._category;

}

set
{
this._category = value;

}
}

public DateTime ReleaseDate
{
get

{
return this._releasedate;

}
set
{
this._releasedate = value;

}
}
}

class Program
{
static void Main(string[] args)
{
ArrayList MyIntegers = new ArrayList();
MyIntegers.Add(100);
MyIntegers.Add(101);

Console.WriteLine(“Prints integers in MyIntegersnn”);
foreach (int i in MyIntegers)
{
Console.WriteLine(i);

}

ArrayList MyChar = new ArrayList();
MyChar.Add(‘a’);
MyChar.Add(‘b’);

Console.WriteLine(“nnPrints characters in MyCharsnn”);
foreach (char c in MyChar)
{
Console.WriteLine(c);

}

/* removes element at 0 index */

MyChar.RemoveAt(0);
Console.WriteLine(“nnPrints characters in MyCharsnn”);

foreach (char c in MyChar)
{
Console.WriteLine(c);

}

Console.ReadLine();

}
}
}

Output

 

Some useful tricks and methods you must explore for ArrayList

Click this

Generics

ArrayLists are good but due to the fact that every element when added to the arraylist,it has to be converted to object (boxing is to be performed) and when the element is taken from it ,it has to be converted by to its original type(unboxing).These boxing and unboxing put lot of performance constraints as far as effective memory utilization is concerned.
Moreover,arraylist is not type safe.Means any type can be added to it and when the code is complied,type mismatch errors are waiting for us

Example

ArrayList MyList = new ArrayList();

MyList.Add(1);
MyList.Add(“hello”);

foreach(int i in MyList)
{

Console.WriteLine(i); // Invalid cast exception is throuwn

}

Here we need to have special collections named as Generic Lists,Dictionaries,Hash tables etc which when declared with a specific type,doesn’t allow us to enter other data types

List

List is a type which allows dynamic allocation of memory.It works best for iterating loops.When a type is specified for the Generic List;the list doesn’t accept any other type behind its defined type

Example

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
List MyList = new List();
MyList.Add(12.2);
MyList.Add(13.6);

foreach (double element in MyList)
{
Console.WriteLine(element);
}
}
}

Output

12.2
13.6
Dictionary

Dictionary is very important as far as speed and reliability is concerned.It stores the key-value collection.Keys should be kept unique for proper code.The keys boost the lookup of the dictionary

Example

using System.IO;
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Dictionary<int,string> MyDictionary = new Dictionary<int,string>();
MyDictionary.Add(101,”Steve”); //First parameter key,second value
MyDictionary.Add(102,”Jobs”);

Console.Write(MyDictionary[101] + “t”);
Console.Write(MyDictionary[102]);
Console.ReadLine();
}
}

Output
Steve Jobs

Hash tables

Hash Table is just like a Dictionary.But performance wise,Dictionary is preferred more over Hash Table due to faster lookups

Example

using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main()
{
Hashtable MyHash = new Hashtable();
MyHash[1] = “Steve”;
MyHash[2] = “Jobs”;
MyHash[3] = “We Miss You”;

foreach (DictionaryEntry entry in MyHash)
{
Console.WriteLine(“{0}, {1}”, entry.Key, entry.Value);
}
}
}

Output

1, Steve
2, Jobs
3, We Miss You
Note: Hash Tables may store different data types but it is a poor programming practice to make your logic error-prone

Generic Classes

It is quite easier to implement class of generic type.Have a look at the example below.Run it by yourself to understand the logic

Example

using System;
using System.Collections;
using System.Collections.Generic;

class MyClass
{
MyType _name;
MyType _age;

public MyClass(MyType type)
{

this._name = type;
this._age = type;
}

public MyType _Name
{
get
{
return this._name;

}

set
{
this._name = value;

}

}

public MyType _Age
{
get
{
return this._age;

}

set
{
this._age = value;

}

}

public void WriteName()
{
Console.Write(“Name:{0} “,_Name);

}

public void WriteAge()
{
Console.Write(“Age:{0}”, _Age);

}

}

class Program
{
static void Main()
{

MyClass _name= new MyClass(“Wilson”);
MyClass _age = new MyClass(32);

_name.WriteName();
_age.WriteAge();

Console.ReadKey();

}
}

Output

Name:Wilson Age:32
See Linked Lists ,Sorted Lists ,ReadOnly Collections , Capacity

I will upload the free downloadable tutorials with examples on the following topics

    ListDictionary
    HybridDictionary
    SortedDictionary
    StringDictionary
    NameValueCollection
    DictionaryEntry

Early Vs Late Binding

Binding is the operation performed by the compiler to assign an object to a variable.
Early Binding is a means by which we assign an object to a variable of specific type so that the compiler knows before its execution about its type.This form of binding is the performance critical as it involves faster memory operations
In Late Binding,we do not use a specific type for a variable when an object is assigned to it.The compiler has to understand the type in the execution process

Examples

Early Binding

class myClass
{

int i=2;
int j=3;

myClass(int _i,int_j)
{

this._i=i;
this._j=j;

}
}

Late Binding

class myClass2
{

int i=2;
double j=3.2;

myClass(object _k)
{

this._k=i*j;

}
}

Namespaces

Refer the article at the mentioned link from msdn.It is so simple to understand namespaces


Namespaces in C#

 

Copyrighted.com Registered & Protected 
TS6K-RO6Z-PBJY-GANP


Syed Adeel Ahmed
Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.