Sunday, 13 April 2014

11: Inheritance in C#

Inheritance

The physical features of a child are similar to his/her parents, because child having inherited features from his/her parents.


For Example:


Definition:

The creation of new class based on the attribute, property and methods of existing class. The created class is derived class or child class and the existing class is based or parent class.
It is the backbone of the OOP which allow reusability of inherited attributes method etc.

For Example:

A vehicle class which has one attribute and one method, as we know that each vehicle either 2 wheelers or 4 wheelers both have color and speed.
In this way we can inherit two wheelers and four wheelers with the vehicle class in order to use its attribute and method like child uses home, laptop and car of its parents.


Purpose:


The purpose of inheritance is reusability which allows us to use common methods attribute among classes without recreating them.
Inheritance is widely used for
  1. Generalization
  2. Specialization
  3. Extension

Generalization

By the help of inheritance we can implement generalization, like we have seen vehicle class example where vehicle is generalize for all type of vehicles (two, three, four wheelers etc.).

Specialization

By the help of inheritance we can implement specialization, like bus, car class is specialized class, because when we talk about four wheeler its means that we are talking generalized class which have attribute and methods which are common for all four wheeler, but when we talk about particular four wheeler like bus or car its means we are talking about specialization.

Extension

By the help of inheritance we can extend the functionalities of derived class by creating more methods and attribute that are not present in the base class.

Syntax:

<Derive class name> :< base Class>
Inheritance in C# is done by using Colon.

Example
class Animal
{
public void Eat()
{
                    Console.WriteLine("All animals are eating");
}
}

class Cat : Animal
{
public string color = "Black";     
}

What will happen when we make an object of Cat class?


As you can see eat method is not present in the Cat Class but due to inheritance it shows eat method.



Main method will be.

static void Main(string[] args)
{
Cat myCat = new Cat();
       Console.WriteLine(myCat.color);
       myCat.Eat();
       Console.ReadLine();
}

Output:
Black
All animals are eating.


Constructor Chaining

What will happen when we use default constructor in both classes?

Example

class Animal
{
public Animal()
{
                    Console.WriteLine("hi, this is Animal Constructor");
          }
       
public void Eat()
{
                             Console.WriteLine("All animals are eating");
}
}

class Cat:Animal
{
public string color = "black";
public Cat()
{
                             Console.WriteLine("hi, this is Cat Constructor");
}
}
static void Main(string[] args)
{
Cat myCat = new Cat();     
Console.WriteLine(myCat.color);
myCat.Eat();
Console.ReadLine();
}

Output:

Red area shows constructor of Animal class but as you can see I have created Cat class object only, this type of functionality is called constructor chaining.
After Animal class’s constructor all remaining code will runs normally.

For example

Consider all classes have constructor


  1. Vehicle constructor will be call
  2. Four wheelers class constructor will be call
  3. Then car constructor will be call


Base keyword

By the help of base keyword we can access base class (parent class) methods and variables; we can also re-declare variables and methods in derived class.
We cannot use base keyword for static methods in base class.

Example:

class Animal
{
public Animal()
{
                    Console.WriteLine("hi, this is Animal Constructor");           
}       
public void Eat()
{
                    Console.WriteLine("All animals are eating");
}       
}
class Cat:Animal
{
public string color = "black";      
public void CatEat()
{
base.Eat();
Console.WriteLine("but, Cat also eats");
       }
}


static void Main(string[] args)
{
Cat myCat = new Cat();
myCat.CatEat();
Console.ReadLine();
}


Output:

hi, this is animal constructor
All animals are eating
But, Cat also eats

In the above example we created another method named CatEat which calls parent class (base class) method (we can also use base keyword for variables) and then its own code.


Constructor Inheritance

By the help of base keyword we can inherit construct of derived class with the particular constructor of base class (like in case of constructor overloading).

Example:

class Animal
{
public Animal()
{
                    Console.WriteLine("hi, this is Animal default Constructor");           
}
public Animal(string spec)
{
                    Console.WriteLine("hi, this is {0} Animal Constructor",spec);
}      
}
class Cat:Animal
{
public string color = "black";
public Cat():base("special")
{
                    Console.WriteLine("hi, this is Cat Constructor");
}
}
static void Main(string[] args)
{
Cat myCat = new Cat();
Console.ReadLine();
}

Output:

Hi, this is special Animal Constructor
Hi, this is Cat Constructor

Noticed that I have only create Cat Object but it Shows Animal class Constructor which have one parameter.
When we create object of class, it first execute constructor of a class, but in this case when compiler comes at constructor it find base keyword with one parameter (string type) it go to base class and find constructor with one parameter(string) and execute it and return back to the constructor of derived class(Cat Class).

Tuesday, 8 April 2014

10: Array in C#

Single dimension Array

An array always stores value of single data type placed in contiguous memory locations and these values are reference using a common array name.
These elements are accessed using subscripts or index numbers that determine the position of the element in the array list.

C# array supports zero-based index values in an array. This means that the first array element has index number zero and the last element has index n-1, where n stand for total number of array.
Syntax:

datatype[] arrayName;
arrayName=new Datatype[int(length of array)];
or
datatype[]  arrayName=new Datatype[int(length of array)];

Declaring and Initializing Array

string[] studentsName;// declaration of string array

Array initialize by the new keyword when we specify the size of the array, the new keyword allocates memory to the array.

studentsName = new string[4];// create string array object

Or we can create and declare the array in one line
string[] studentsName= new string[4];

Initialization of array in one statement

string[] studentsName = new string[] {
            "Ahsan","Faizan","Majid","Abdul Ahad"
            };

Console.WriteLine(studentsName[3]);// it will print Abdul Ahad

Initialization of array separately

string[] studentsName = new string[4];
studentsName[0] = "Ahsan";
studentsName[1] = "Faizan";
studentsName[2] = "Majid";
studentsName[3] = "Abdul Ahad";

Console.WriteLine(studentsName[3]);// it will print Abdul Ahad

Initialization of array at runtime

Example:

string[] studentsName = new string[4];

Console.WriteLine("Please Enter Students Name\n");

for (int i = 0; i < 4; i++)
{
studentsName[i] = Console.ReadLine();
}

Console.WriteLine("\nList Of Students is\n");

for (int i = 0; i < 4; i++)
{
Console.WriteLine(studentsName[i]);
}

Output:



Multi Dimension Array

By the help of multi Dimension Array we can store combination of values of single dimension in two or more dimensions.
These dimensions are represents by columns and rows like matrix or MS Excel sheet.

00
01
02
10
11
12
20
21
22
30
31
32
40
41
42
50
51
52

In matrix 00, 01, 02 …are positions of rows and columns but in multi- dimension array these are indexes of rows and columns.

There are two type of multi- dimension array.

  1. Rectangular Array
  2. Jagged Array


Rectangular Array

Rectangular multidimensional array have constant number of columns in each rows.
For example:
3X3, 2X2, 5X5 matrix

Syntax:

datatype[,] arrayName;
arrayName=new Datatype[int(no of rows), int(no of columns)];
or
datatype[,]  arrayName=new Datatype[int(no of rows), int(no of columns)]

Example:

int count = 0;

string[,] studentsName = new string[3,4];

//inserting values to array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
studentsName[i, j] = count.ToString();
count++;
}
}
//printing values from array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(studentsName[i, j]+"  ");
}
Console.WriteLine();
}

Output:
0        1        2        3
4        5        6        7
8        9        10      11

Notice that there are 3 rows but each row has 4 column.


Jagged Array

Jagged multidimensional array may have different number of columns in each row.

For example:


Syntax:

datatype[][] arrayName;
arrayName=new Datatype[int(no of rows)][ ]
//we leave column [] empty because jagged array allow us to increase/decrease number of columns in any rows
or
datatype[,]  arrayName=new Datatype[int(no of rows)][ ];

Example:

Coding:


string[][] classRoom = new string[4][];
            classRoom[0]=new string[]{
            "student1","student2","student3","student4","student5"
            };
            classRoom[1] = new string[]{
            "student1","student2","student3"
            };
            classRoom[2] = new string[]{
            "student1","student2","student3","student4"
            };
            classRoom[3] = new string[]{
            "student1","student2"
            };

for (int i = 0; i < classRoom.GetLength(0); i++)
{
Console.WriteLine("student at class room {0}",i+1);

          for (int j = 0; j < classRoom[i].GetLength(0); j++)
          {
                    Console.Write(classRoom[i][j]+", ");
          }

          Console.WriteLine();
          Console.WriteLine();
}

Output:



Properties of Array

string[] mystring = new string[5];

Console.WriteLine(mystring.IsFixedSize);
// it return boolean value(True or False), which indicate the size of array either it is fixed or not
Console.WriteLine(mystring.IsReadOnly);
// it return boolean value(True or False), which indicate the array either it is read only or not
Console.WriteLine(mystring.IsSynchronized);
//it return boolean value, which indicate that array working is well or not while using by multiple threads
Console.WriteLine(mystring.Length);
//it return length of array in 32bit integer value
Console.WriteLine(mystring.LongLength);
//it return length of array in 64bit integer value
Console.WriteLine(mystring.Rank);
//it return dimension of array in our case it return 1
Console.WriteLine(mystring.SyncRoot);
// it return the object which provide access to the array (it return System.String[])

Output:

True
False
False
5
5
1
System.String[]           

Methods of Array

CopyTo method copies all the elements of current single dimension array to another single dimension array.

Example:
string[] Companies = new string[]{
            "Microsoft","Dell","Samsung"
            };
           
string[] newCompanies=new string[3];
Companies.CopyTo(newCompanies,0);

foreach (var item in Companies)
{
Console.WriteLine(item);
}

Output:
Microsoft
Dell
Samsung

SetValue method allows you to set the value to array at specific index.

Example:
string[] Companies = new string[]{
            "Microsoft","Dell","Samsung"
            };

            Companies.SetValue("HP", 1);
            foreach (var item in Companies)
            {
                Console.WriteLine(item);
            }
Output:
Microsoft
HP
Samsung

GetLength method returns number of element in the array.

Example:
Console.WriteLine(Companies.GetLength(0));
Output:
3

GetUpperBound method returns the last index (upper bound) of the array.

Example:
Console.WriteLine(Companies.GetUpperBound(0));
Output:
2

 GetLowerBound method returns the initial index (lower bound) of the array.

Example:
Console.WriteLine(Companies.GetLowerBound(0));
Output:
0

 GetValue method returns the value of the array at specific index

Example:
Console.WriteLine(Companies.GetValue(0));
Output:
Microsoft


Array Class
Array class provides many properties and methods for create and manipulate array.

Array Class Sort Method

Example:
string[] Companies = new string[]{
            "Microsoft","Dell","Samsung"
            };

            Array.Sort(Companies);
            foreach (var item in Companies)
            {
                Console.WriteLine(item);
            }
          
Output:
Dell
Microsoft
Samsung

Array Class Clear Method
This method clears all the element of the array.

Example:
string[] Companies = new string[]{
            "Microsoft","Dell","Samsung"
            };

            Array.Clear(Companies, 0, 3);
            foreach (var item in Companies)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();

Output:
Nothing print due to clear method

Array Class Reverse Method
This method reverse all the element of the array.

Example: 
string[] Companies = new string[]{
            "Microsoft","Dell","Samsung"
            };

Array.Reverse(Companies);
foreach (var item in Companies)
{
Console.WriteLine(item);
}

Output:
Samsung
Dell
Microsoft

Array Class IndexOf Method
This method returns index of specific element of the array.

Example:

string[] Companies = new string[]{
"Microsoft","Dell","Samsung"
};
Console.WriteLine(Array.IndexOf(Companies,"Dell"));

Output:
1