क्लास कंस्ट्रक्टर एक क्लास का एक विशेष सदस्य फ़ंक्शन होता है जिसे जब भी हम उस क्लास के नए ऑब्जेक्ट बनाते हैं तो उसे निष्पादित किया जाता है। डिफ़ॉल्ट कंस्ट्रक्टर का कोई पैरामीटर नहीं होता है।
सी# में डिफॉल्ट कंस्ट्रक्टर के साथ काम करने का तरीका दिखाने वाला एक उदाहरण निम्नलिखित है -
उदाहरण
using System;
namespace LineApplication {
class Line {
private double length; // Length of a line
public Line(double len) { //Parameterized constructor
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
} आउटपुट
Object is being created, length = 10 Length of line : 10 Length of line : 6