Thuta Learning
C#
IntermediateProgrammingbeginner

Constructors

Constructor သည် object create လုပ်တဲ့အချိန် အလိုအလျောက်ခေါ်သုံးတဲ့ special method ပါ။ Object စတင်ဖန်တီးချိန်မှာ value တွေ initialize လုပ်ဖို့ အရမ်းအသုံးများပါတယ်။ Constructor name သည် class name နဲ့တူရပြီး return type မရှိပါ။

csharp
class Car
{
    public string Model;
    public int Year;

    public Car(string model, int year)
    {
        Model = model;
        Year = year;
    }

    public void ShowInfo()
    {
        Console.WriteLine($"{Year} {Model}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car("Mustang", 2024);
        myCar.ShowInfo();
    }
}

Constructor ရဲ့အသုံး

  • new Car("Mustang", 2024) ခေါ်တဲ့အချိန် constructor က parameter နှစ်ခုလက်ခံပါတယ်။
  • Model နဲ့ Year ကို object စတင်ချိန်မှာ တန်ဖိုးထည့်ပေးပါတယ်။
  • Object တစ်ခုဖန်တီးပြီးမှ value ထည့်မေ့တာမျိုးကို constructor က လျော့စေပါတယ်။
You should see
2024 Mustang
Constructors | Thuta Learning