একটি ক্লাস কনস্ট্রাক্টর একটি ক্লাসের স্পেশাল মেম্বার ফাংশন যা নতুন অবজেক্ট তৈরি হওয়ার সময় এক্সিকিউট হয়। একটি ডিফল্ট কনস্ট্রাক্টরের কোনো প্যারামিটার (parameter) থাকে না।
উদাহরণ
using System;
namespace LineApplication {
class Line {
private double length;
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());
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
নোট: এই উদাহরণে প্যারামিটারাইজড কনস্ট্রাক্টর (parameterized constructor) দেখানো হয়েছে। ডিফল্ট কনস্ট্রাক্টর হলে প্যারামিটার থাকবে না, যেমন public Line() { }।