C# Classes - Constructor
We may like to assign the values of the length and breadth as soon as we create the instance of the class. A constructor does that job.
Let us take a look at the following code
using System; using System.Collections.Generic; using System.Linq; using System.Text; class Rectangle { private int length, breadth; private int area; public Rectangle(int length_input, int breadth_input) { length = length_input; breadth = breadth_input; } public int calculatearea() { area = length*breadth; return (area); } } namespace ClassRectangle { class Program { static void Main(string[] args) { int area1; Rectangle rect1 = new Rectangle(10, 20); area1 = rect1.calculatearea(); Console.Write("Area of Rectangle is "); Console.WriteLine(area1); Console.ReadLine(); } } } |
Area of Rectangle is 200 |
The difference is, this time we are able to assign the values of the variables length and breadth as soon as we create an instance of the of the class Rectangle. This is done using the contructor
public Rectangle(int length_input, int breadth_input) { length = length_input; breadth = breadth_input; } |
A constructor is a special Method. It has the same name as the class. This special method gets automatically called when an instance of the class is created.
Take a look at how the instance of the class is created this time.
Rectangle rect1 = new Rectangle(10, 20); |