Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Constructor trong chương trình C#

Class constructor là member function đặc biệt thực thi khi tạo object mới của class.

Constructor có tên trùng class và KHÔNG có kiểu trả về.

Constructor tên trùng class:

class Demo { 
    public Demo() {} 
}

Ví dụ:

Ví dụ

using System; 
namespace LineApplication { 
    class Line { 
        private double length; 
        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(); 
            line.setLength(6.0); 
            Console.WriteLine("Length of line : {0}", line.getLength()); 
            Console.ReadKey(); 
        } 
    } 
}

Kết quả

Object is being created
Length of line : 6