Constructor ของคลาสเป็นฟังก์ชันสมาชิกพิเศษที่ทำงานเมื่อสร้างออบเจ็กต์ใหม่ Default Constructor คือ Constructor ที่ไม่มีพารามิเตอร์
ตัวอย่างการใช้งาน Default Constructor ใน C#
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