ตัวสร้างคลาสเป็นฟังก์ชันสมาชิกพิเศษของคลาสที่ดำเนินการทุกครั้งที่เราสร้างวัตถุใหม่ของคลาสนั้น
คอนสตรัคเตอร์มีชื่อเหมือนกันทุกประการกับชื่อคลาส และไม่มีประเภทการส่งคืน
ตัวสร้างมีชื่อเดียวกับชื่อคลาส -
class Demo {
public Demo() {}
} ต่อไปนี้เป็นตัวอย่าง −
ตัวอย่าง
using System;
namespace LineApplication {
class Line {
private double length; // Length of a line
public Line() {
Console.WriteLine("Object is being created");
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
} ผลลัพธ์
Object is being created Length of line : 6