Saturday, May 14, 2011

Enumeration

Enumeration are declared using enum keyword. Enumeration are distinct type consisting of a set of names that are constant.
For example we know that days in week are constant so we can use enum for days and month also.
Each enum type has a corresponding integral type called the underlying type of the enum
type. This underlying type must be able to represent all the enumerator values defined in
the enumeration. An enum declaration may explicitly declare an underlying type of byte,
sbyte, short, ushort, int, uint, long, or ulong. Note that char cannot be used as an underlying
type. An enum declaration that does not explicitly declare an underlying type has an
underlying type of int.


Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace test_practise
{
    public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
    class Program
    {
        static void Main(string[] args)
        {
            Days day = Days.Monday;
            Console.WriteLine((int)day);
            Console.WriteLine(day);
            Console.ReadLine();
        }
    }
}


You will see output 0. You can change the value of Monday from 0 to 1 by assigning value to Monday


public enum Days { Monday=1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

Tuesday, March 1, 2011

Interface

Interface is a comunicating media between two mediums. In c# multiple inheritance is not allowed that's why interface are used to fulfil the needs of multiple inheritance. As c# does not support multiple inheritance then it is necessary that the class can inherit the behaviour of more than one class, that's what interface provides us. In multiple inheritance we had a problem that if a class has two base class and both have some same methods then which method to call. Classes can inherit multiple interface.
Interface are contract of rules that a class which inherits it must follow(i.e must implement the method which are defined in interface). Interface contains method that do not contain any implementation just contain declaration of that method and the class which inherits it must implement those method. Interfaces can contain properties, indexers, and events but interface cannot contains field and interface cannot be instantiate.


Example



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace blog
{
    class Program
    {
        static void Main(string[] args)
        {
            circle objc = new circle();
            objc.fill();
            square objs = new square();
            objs.fill();
            line objl = new line();
            objl.draw();
            Console.ReadKey();
        }
    }
    interface fill
    {
        void fill();
    }
    class shapes  {
        public void draw()  {
            Console.WriteLine("shape Draw");
        }
    }
    class circle : shapes,fill    {
        public void fill()        {
            Console.WriteLine("Circle Fill");
        }
    }
    class square : shapes, fill    {
        public void fill()        {
            Console.WriteLine("Square Fill");
        }
    }
    class line : shapes    {
    }
}

Wednesday, February 16, 2011

Mathematical Table

Mathematical Table
Lets make a Program that take input and will show mathematical table.



static void Main(string[] args)
        {
            int table;            
            Console.WriteLine("Enter Table Number");
            table = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i < 13; i++)
            {
                Console.WriteLine(table + " x " + i + " = " + i * table); 
            }
            Console.ReadKey();   
        }


Lets make another program that will show mathematical table from 1 to 12.



static void Main(string[] args)
        {
            for (int i = 1; i < 11; i++)
                for (int j = 1; j < 13; j++)
                    Console.WriteLine(i + " x " + j + " = " + i * j);
            
            Console.ReadKey();   
        }

Factorial Program

Factorial Program
Lets make a factorial program using FOR loop. First of all we should understand what's the mechanism of factorial. Factorial number are those number which multiply themselves by its lower number. If you want to find out factorial of 4 that will be ( 4 x 3 x 2 x 1 ) 24.



static void Main(string[] args)
        {
            int num;
            int result=1;
            Console.WriteLine("Enter Any Number To Find its Factorial");
            num = Convert.ToInt32(Console.ReadLine());
            for (int i = num; i > 1 ; i--)
                result *= i;
            Console.WriteLine("Factorial of "+ num +" is " + result);
            Console.ReadKey();
            
        }

Monday, February 14, 2011

Iteration Statements

Iteration Statements

We have discuss about conditional statements that what will you do if you have to take decision among multiple statements but if you have to repeat one or more statements 100 or more times then what will you do you can't write that statements 100 times and it will also reduce efficiency of you program. Iteration Statements are used to repeat statements number of times you want. Iteration or sometime called loop are used when you have to repeat a certain part of statements over and over until the expression or condition you have applied is met. Following are some Iteration Statements of Loops

  • For Loop
  • While Loop
  • Do-While Loop

For Loop
The syntax of For Loop is

for ([initializer] ; [condition] ; [iterators])
{
// For Loop Statement Body
}

Initializer : initializer is the starting value for the loop.
Condition : relational test that determines whether to execute the for loop statement body or not
Iterator : Iterator control the loop by increment o decrement (or any logical operation you want to apply )


How its Works
First of all the initializer are executed and initialize whatever value is given.
Then the condition expression is executed and if it is TRUE it will enter FOR LOOP BODY.
The FOR statement body is executed and after it iterators expression is executed.
After iterator the condition expression is executed to check if condition is still TRUE to enter the FOR body or FALSE to skip the body and end the loop.


Example


static void Main(string[] args)
        {
            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine("I = " + i);
            }
            Console.ReadKey();
        }

While Loop
The syntax of while loop is


while(condition)
{
// While Loop Block
}


While loop have only condition in its structure but initializer is made before while body and iterator can be make in while loop block.


How its Works
Initialization is make before while loop.
Condition is test to enter WHILE loop or skip the loop.
If condition is TRUE then it will enter while loop and after executing while block condition will be checked again.
And Iteration can be made inside while loop block.
Let see an example to make it clear


Example



static void Main(string[] args)
        {
            int i = 0;
            while (i < 9)
            {
                Console.WriteLine("I = " + i);
                i++;
            }
            Console.ReadKey();
        }

do-While Loop
do-while is same as while loop with additional keyword of do. do-while executes statement at least one time whether the condition is true or false.
The Syntax of do-while loop is


do
{
//do-while loop block
}
while(condition);


How its Works
Do-while loop start executing from do.
First of all do-while block is executed doesn't matter the condition is TRUE of FALSE.
After it the condition is tested to check whether to repeat the do-while body again or not. 


Example



static void Main(string[] args)
        {
            int i = 0;
            do
            {
                Console.WriteLine("I = " + i);
                i++;
            }
            while (i < 9);
            Console.ReadKey();
        }




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