Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0106 Constructor

Constructors are used to initialize the object. Constructors have the same name with the class but their return types are empty. class Rectangle{ public Rectangle(){ } } Constructors can have parameters. The following code uses the contructor to initialize the fields. using System; class Rectangle{ public int Width; public int Height; public Rectangle(int w, int h){ Width = w; Height = h; } } class Program { static void Main(string[] args) { Rectangle r = new Rectangle(1, 2); Console.WriteLine(r.Width); } } The output: 1 Constructors can have the following modifiers: public internal private protected unsafe extern