Add constructor to class : Constructor : Class C# Examples


C# Examples » Class » Constructor »

 

Add constructor to class






A constructor initializes an object when it is created.
A constructor has the same name as its class
A constructor is syntactically similar to a method.
Constructors have no explicit return type.

The general form of constructor is shown here:




    
access  class-name(  )  {
//  constructor  code
}
    
   
  
   

You can use a constructor to give initial values to the instance variables.




    
using  System;  
  
class  MyClass  {  
    public  int  x;  
  
    public  MyClass()  {  
        x  =  10;  
    }      
}      
      
class  ConsDemo  {      
    public  static  void  Main()  {      
        MyClass  t1  =  new  MyClass();  
        MyClass  t2  =  new  MyClass();  
  
        Console.WriteLine(t1.x  +  "  "  +  t2.x);  
    }      
}
    
   
  
   



Output

10 10


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Class
» Constructor