Constructor in C# with example
Constructor
Constructors have the same name as the class itself. Secondly, they do not specify a return type, not even void. Because they do not return any value. It would be simpler and more concise to initialize an object when it is first created.
Example:
using System;
class Rectangle
{
int length;
int width;
public Rectangle(int p, int q) // Defining constructor
{
length=p;
width=q;
}
}
public int RectArea()
{
return(length*width);
}
}
class RectangleArea
{
public static void main()
{
Rectangle r1=new Rectangle(10, 7);
int area=r1.RectArea();
Console.WriteLine("The Area of Rectangle is: "+area);
}
}
Output:
The Area of Rectangle is: 70