Wednesday, 3 July 2013

C# Class

In C# , Class is known as a Template from which we can create so many object of same type. In real world we can compare the Class as a Model , and object as a thing which is created based on that model.

For Example :

Class  is a Template or Model, Object is a Instance of that Class

Real World Comparison

Class (Template) : We take a Bike Company , which have introduced a new model "Spl Plus" . Here Model refers to a Class it is a template .

Object (Instance of a class) : Based on that Model "Spl Plus" of the Bike , That company creates a 10,000 bike. Here the 10,000 bikes created based on that model refers to Object, Which is an Instance of that Model.

Class Definition:
 First Starts with a Access Specifier followed by keyword class and then classname. Class consists of Properties, Variables, Methods, Indexers, Events, Delegates etc

Declaration of Property
//Property
    <access specifier> <data type> PropertyName{set;get;}
    

Declaration of Variable
//variables
    <access specifier> <data type> variablename;
    

Declaration of Method
//methods
    <access specifier> <return type> methodname(parameter_list) 
    {
        // method body 
    }

Declaration of Class
//Class
    <access specifier> class classname{ }

Whole Class Definition
<access specifier> class  class_name 
{
    // member variables
    <access specifier> <data type> variable1;
    <access specifier> <data type> variable2;
    ...
    <access specifier> <data type> variableN;
    // member methods
    <access specifier> <return type> method1(parameter_list) 
    {
        // method body 
    }
    <access specifier> <return type> method2(parameter_list) 
    {
        // method body 
    }
    ...
    <access specifier> <return type> methodN(parameter_list) 
    {
        // method body 
    }
}

Example :

SplPlus is class or Template
public class  SplPlus
{
    private int cc = 120;              //variables
    public int NoOfWheel{set;get;}     //property
    
    public void Start()                //method
    {
        // method body 
    }
    public int Speed() 
    {
        return 70;
    }

}
/* Now creating a 2 instance for that SplPlus class in  Program Class */
public class Program
{    
    public static void Main(string []args)                //main method
    {
         SplPlus ins1=new SplPlus(); //1 instance,1 bike in same model
         SplPlus ins2=new SplPlus(); //2 instance,2 bike in same model
         ins1.Start(); 
         ins2.Start();                                                                                                           
    }

}

No comments:

Post a Comment