Thursday, January 27, 2011

Conditional Statements

Conditional Statements
Compiler executes code from top to bottom and line to line. If you have to make decision for different users or you have to change control of code, what will you do? For this Control Statements are used to make decisions
  • IF-Statement
  • IF-ELSE Statement
  • IF-ELSE-IF Statement
  • Switch Statement
IF-Statement
The syntax for IF statement is 

if(expression)
{
// Statement block
}

Expression written in the brackets helps relational test to be performed and tells that whether or not to execute the statements inside the IF statement block depends on the outcome of relational test or operations. If operation is TRUE then it will execute IF statement block and if FALSE then it will skip IF statement block.

Example
Making a program using IF statement to show ODD and EVEN number.

static void Main(string[] args)
        {
            int value;
            string result = "Number is Even";
            Console.WriteLine("Type any Number");
            value = Convert.ToInt32(Console.ReadLine());
            if (value % 2 == 1)
            {
                result = "Number is Odd";
            }
            Console.WriteLine(result);
            Console.ReadKey();
        }


IF-ELSE Statement
In previous example(odd and even program) I have set result as Number is Even at the moment the result was defined. So the result variable will only changed if number is odd, but I want to make decision based on the input whether number is even or odd. The IF-Else Statement is suitable for this. 

The syntax for IF-ELSE statement is

if(expression)
{
// IF statement block : TRUE
}
else
{
// ELSE statement block : FALSE
}

If expression (relational operation) is TRUE then IF statement block is executed if expression is FALSE then it will enter the statement block following the else keyword that is ELSE statement block.


Example
Making a program using IF-ELSE statement to show ODD and EVEN number.

 static void Main(string[] args)
        {
            int value;
            string result;
            Console.WriteLine("Type any Number");
            value = Convert.ToInt32(Console.ReadLine());
            if (value % 2 == 1)
            {
                result = "Number is Odd";
            }
            else 
            {
                result = "Number is Even";
            }
            Console.WriteLine(result);
            Console.ReadKey();
        }


IF-ELSE-IF Statement
In previous example we have work on two decisions that is "Number is Even" or "Number is Odd". If we have to work on multiple decisions like days in week or months in year. For that we have IF-ELSE-IF statement. 
The syntax for IF-ELSE-IF statement is

if(expression)
{
}
else if(expression1)
{
}
else if(expression2)
{
}
.
.
.
.
.
else
{
}

Example
Make a program that will take an number input and will show you that which number you have typed.

static void Main(string[] args)
        {
            int num;
            Console.WriteLine("Type Number between 1 - 6");
            num = Convert.ToInt32(Console.ReadLine());
            if (num == 1)
                Console.WriteLine("You have Typed ONE");
            else if (num == 2)
                Console.WriteLine("You have Typed TWO");
            else if (num == 3)
                Console.WriteLine("You have Typed THREE");
            else if (num == 4)
                Console.WriteLine("You have Typed FOUR");
            else if (num == 5)
                Console.WriteLine("You have Typed FIVE");
            else if (num == 6)
                Console.WriteLine("You have Typed SIX");
            else
                Console.WriteLine("Number Out of SCOPE");
            Console.ReadKey();
        }
Switch Statement
Another type of control statement is switch statement that can handle multiple decisions by passing control to case statements which are inside switch body.
The syntax of switch statement is.
switch(expression)
{
 case1:
// case1 statement
break; // break or any statement that can take control of transferring case body
case2:
// case2 statement
break;
.
.
.
.
default:
// default statement
break;
}
In switch statement , which case has to be executed is determine by expression. If value of expression is 1 then case1 will be executed and if expression do not match any case then default case will be executed. The break statement control from falling through to the next case statement.
Example
Let make the same program of IF-ELSE-IF in Switch statement.
static void Main(string[] args)
        {
            int num;
            Console.WriteLine("Type Number between 1 - 6");
            num = Convert.ToInt32(Console.ReadLine());
            switch(num)
            {
            case 1:
                Console.WriteLine("You have Typed ONE");
                break;
            case 2:
                Console.WriteLine("You have Typed TWO");
                break;
            case 3:
                Console.WriteLine("You have Typed THREE");
                break;
            case 4:
                Console.WriteLine("You have Typed FOUR");
                break;
            case 5:
                Console.WriteLine("You have Typed FIVE");
                break;
            case 6:
                Console.WriteLine("You have Typed SIX");
                break;
            default:
                Console.WriteLine("Number Out of SCOPE");
                break;
            }
            Console.ReadKey();
        }

Wednesday, January 19, 2011

Interoperability

Cross Language Interoperability
Interoperability is system that works together. Language Interoperability gives ability to user to interact with code which is written in different language. Common Language Runtime provides built-in support for Language interoperability, but it does not guaranty that code written in one language can be used in other language. To ensure that language of one code can interact with code of another language, a set of language features and rules for using them has defined that is Common Language Specification.

Example
Let make a program to write code in VB and interact with c#. Lets create a class in VB and use it in C#.
Create a New Program and select VB language and Class Library from Templates


Now Create a New C# Console Application then go to solution explorer and right click on your project then go to Add Reference then click browse tab. Now open you project (which was created in VB) then open Bin then Debug. Inside debug you will see dll file of you VB project, add this file to your project.



After adding dll file you can use VB project in c#. 


Before creating instance of class (VB) use namespace of you project (i.e using interoperability1) or you can also create instance by calling fully name (i.e interoperability1.Class1 objEmp = new interoperability1.Class1();).

  

Tuesday, January 18, 2011

Accessibility Level

Accessibility Level



Destructor

Destructor
Destructor have same name as class name. Destructor is used to destruct instance of class. Destructors enable the runtime system to recover the heap space and to terminate file I/O that is associated with the removed class instance. A class can only have one destructor. In c# we can’t define destructor in structs they are only used in classes. Destructor can’t be inherited or overloaded and we can’t call destructor explicitly they are invoked automatically (.Net frameworks Garbage Collector (GC) has control over destructor). Destructor does not have parameter or any modifiers.


 Example
To see working of destructor let us consider a example. Take three classes Human,Male and Stud. Stud is most derived class and Human is least derived class. Every class contain a destructor and we will create instance of most derived class(i.e. Stud) and destructor will called automatically in order from Stud then Male then Human.


Output will be
Student Class Destructor
Male Class Destructor
Human Class Destructor  

Monday, January 17, 2011

How To call Constructor from another Constructor

Calling Constructor From Another Constructor
We can also call constructor from another constructor.


Example




We have use this() after every constructor which mean that before executing the constructor go to this() constructor. Human : this("Hello"). It means that before executing Human default constructor compiler will execute Human constructor which takes string as a argument (i.e. Human(string a).




Constructor Chaining

Constructor Chaining
You can achieve constructor chaining through inheritance. Constructor chaining is a process in which the first task of derived constructor is to call its base class constructor. There can be a number of classes in an inheritance chain. In constructor chaining the derive class will call its base class and this process will continue until it reaches its top most class and then all constructor will execute as a chain from top till original class.

Example
Let make a program to understand the mechanism of constructor chaining.


We have create three class. Stud, Male and Human. Stud is inherited from Male and Male is inherited from Human. Human is at the top and Stud is in bottom.



We have create an object of Stud class. What will happen if we create Stud object. Compiler will go to Stud constructor and before executing the Stud constructor it will go to its base class  (i.e. Male). Before executing Male constructor it will go to its base class (i.e.Human). Now complier have reached at the top and will start executing base constructor (i.e Human) then its (Human) derived class constructor (i.e. Male) then its (Male) derived class constructor (i.e Stud).


Constructor Overloading

Constructor Overloading
Overloading of constructor is same as overloading of method. Constructor overloading is having two or more constructor within a same class with different parameters.
We can achieve overloading by
  • Number of Parameters
  • Types of Parameters
  • Arrangement of Parameters


Example
Number of Parameters


Types of Parameters


Arrangement of Parameters


Private Constructor

Private Constructor
You can also use make your constructor private. If constructor is private so it restricts the object to instantiate using new keyword. You can’t create object of private constructor but you can use access static members of class by calling them from class name. Private constructors are used when you don’t want to create an object of class or you don’t want the class to be inherited.


Example



In this program we have create a private constructor and variable Name as static. First we will look that what happen if we instantiate an object of private constructor.




Can't instantiate an object of private constructor. You can see that it says that you can't access the object Human() because of its protection level.


Now without instantiating object we will use static variable.






We have to call static variable with class name as we have done here Human.Name.






Now we will make another class and will inherit the Human class to see that the class contain private constructor can be inherit or not.




It gives the same error when we were creating object of private constructor.


Read about Constructor, Constructor Overloading, Constructor Chaining

Sunday, January 16, 2011

Constructor

Constructor
Constructor is a special method without any return type and have same name as class name. Constructor is used to initialize an object of a class and it runs or executes automatically when you create an object. Constructors are called only once per creation of an object while regular methods can be called many times. Constructor can be private, public, static and protected. We can also overload constructor.

In c# constructor are called using new keyword.
Car objcar = new Car();
When you use new keyword then object is created and runtime will construct that object by using the definition of the class. Then it grab a piece of memory and fills with the fields (variable or methods) defined by the class and then a constructor is invoked to perform any initialization required.

Constructors are generally of following types
  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

Default Constructor
When you create class without any constructor then compiler will provide you parameterless constructor with no body that parameterless constructor is called default constructor.

To explain default constructor we will make two program, in first program we will use default constructor which is provided by compiler and secondly we will create our own default constructor . 

We can't see default Constructor provided by compiler (but it is present in the class) thats why we will make our own default constructor to show that both are same.

First Program

You can see that we have two variables in class Name and LastName but not constructor but when we create an object of class its working properly. That means there is a default constructor in class provided by compiler but we can't see it.

Second Program

In this program we have two variables in class Name, LastName and a default constructor. When we will create an object the result will be the same as first program.
  
Parameterized Constructor
Constructor that accepts arguments when object is created is called parameterized constructor. Parameterized constructor is not provided by compiler you have to create this constructor. You can use parameterized constructor when you have to initialize data members of a class when object is created.


You can see Human constructor with two parameters Name and Lname. When we create an object we have to provide parameters (e.g. Human objH = new Human("James","Bond");) then Name = James and LastName = Bond will be assigned.

Copy Constructor
Copying values of one object to another object is called copy constructor. If you want to copy values of existing object to another new created object then you have to write method yourself because c# does not provide copy constructor.



We have create two object objH and objAnotherHuman, and will copy data of objH to objAnotherHuman. First we have create objH object and pass parameter(James, Bond) . It means that objH have Name = James and LastName = bond. Now we will create another object objAnotherHuman and will pass objH as parameter . Now copy constructor will copy obj.Name(i.e James) to objAnotherHuman.Name and obj.LastName(i.e Bond) to objAnotherHuman.

If you do not understand what happens or how values are assign in copy constructor then run the program in debugging mode 


Read about Private Constructor, Constructor Overloading, Constructor Chaining

How To call Constructor from another Constructor

Saturday, January 15, 2011

Encapsulation

Encapsulation
The concept of sealing data and methods into an object is known as encapsulation. Its ability is to hide information and internal implementation from the users. Information hiding doesn’t mean to hide information but it means that it gives limited access to user. Access modifiers provides accessibility level for user.



Examples
If you want to meet the president of your country you can’t go directly to meet president. Guard or Security of president will check you and if you have appointment or you have access then you can go to meet him. That’s what encapsulation does. Its guard your data not hides it.  

Take an example of car. All of us drive car when we sit in car and insert key in it and turn it to start the car , the car get started but we don’t know how its starts. We don’t know the internal working of the car. The internal implementation is hidden from the user.


A tracker in a car that helps us trace our car when someone steals our car, so we just let the tracking service provider company know that my car has been stolen I know they can trace it but keep it hidden how are they going to trace it 

Public Access Modifier


We can only access Name because it is public.

Private Access Modifier
To access private variable we have to make property for that variable which will guard the variable and we can access private variable via that property.

Now we can access EngineNo variable via EngineNo1 property.





Protected Access Modifier
Protected variables can be access by inherited class. Let make another class which will inherit clsCar.




Friday, January 14, 2011

Polymorphism

Polymorphism
Polymorphism means having many shapes. Polymorphism allows improved code organization and readability. Its ability of an object is to respond differently to the same message. When a message is send to an object even though we don’t know what specific type it is, but the right thing happens, that’s called polymorphism.

Types of Polymorphism
  • Compile-time polymorphism (early binding)
  • Compile-time polymorphism is also called method overloading.

Compile-Time Polymorphism
Compile-time or Early binding is achieved by Overloading which allows us to have two or more methods in the same class have the same name with different parameters

Example:
We will create a method that will calculate the square of a given number having same name but different data type.


In this program we have use different methods having same name but different parameters this is called overloading.

Run-time polymorphism

Run-time polymorphism is achieved by method overriding.
Overriding allows us to have methods in the base and derived classes with same name and same parameters.

Example:
We have created three classes clsLine, clsTriangle, clsCircle derived from base class clsShapes. clsShapes contain draw() method and clsTriangle and clsCircle contains fill() method. We have declared draw() method as virtual method(virtual keyword is use to modify properties and allow method to be overridden ) so we can override that method  in derived classes by modifying implementation of virtual method with respect to derived classes. So the method to be executed is selected dynamically during run-time.


Now make an object 
clsShapes objShape = new clsTriangle();
and call method draw().


In this picture objShape.draw() is called and you can see the result it says "draw from clsTriangle" which means that draw method is called from clsTriangle class. We can determine the result when we run this program but not on compile-time.