Thuta Learning
C#
IntermediateProgrammingbeginner

Methods

Method ဆိုတာ ပြန်သုံးလို့ရတဲ့ code block တစ်ခုပါ။ Program ကြီးလာတဲ့အခါ code တွေအားလုံးကို Main ထဲမှာပဲထည့်ထားရင် spaghetti ဖြစ်လွယ်ပါတယ်။ Method ခွဲရေးခြင်းက code ကို ဖတ်လွယ်၊ စမ်းသပ်လွယ်၊ ပြင်လွယ်စေပါတယ်။

csharp
class Program
{
    static void SayHello(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }

    static int Add(int x, int y)
    {
        return x + y;
    }

    static void Main(string[] args)
    {
        SayHello("Aung");
        int total = Add(5, 3);
        Console.WriteLine($"Total: {total}");
    }
}

ဒီ code က ဘာလုပ်တာလဲ

  • SayHello method က parameter အနေနဲ့ name လက်ခံပြီး greeting ထုတ်ပါတယ်။
  • Add method က number နှစ်ခုလက်ခံပြီး sum ကို return ပြန်ပေးပါတယ်။
  • void ဆိုတာ return value မရှိဘူးလို့ဆိုလိုပါတယ်။
  • int return type ရှိတဲ့ method က int value ပြန်ပေးရပါတယ်။
You should see
Hello, Aung! Total: 8
Methods | Thuta Learning