การสร้างและเรียก Custom Method (เมธอดกำหนดเอง) ใน C#
Custom Method คือ เมธอดที่นักพัฒนาสร้างขึ้นเองเพื่อทำหน้าที่เฉพาะเจาะจง ช่วยให้โค้ดเป็น Modular, Reusable, Readable
ไวยากรณ์การประกาศ
(Parameter List)
{
// Method Body
return value; // ถ้าไม่ใช่ void
}
ตัวอย่าง: ตรวจสอบ Palindrome แบบ Binary
using System;
public class Demo
{
// 1. Method กลับลำดับบิต
public static long FuncReverse(long num)
{
long rev = 0;
while (num > 0)
{
rev <<= 1; // Shift left
if ((num & 1) == 1) // Check LSB
rev ^= 1; // Set LSB
num >>= 1; // Shift right
}
return rev;
}
// 2. Method ตรวจสอบ Palindrome
public static bool CheckPalindrome(long num)
{
long rev = FuncReverse(num);
return num == rev;
}
// 3. Main เรียกใช้
public static void Main()
{
long num = 5; // Binary: 101
if (CheckPalindrome(num))
Console.WriteLine("Palindrome Number");
else
Console.WriteLine("Not a Palindrome Number");
}
}
ผลลัพธ์
Palindrome Number
แนวทางปฏิบัติที่ดี (Best Practices)
- Single Responsibility: เมธอดทำหน้าที่เดียว
- Naming: PascalCase, Verb Phrase (
CalculateTotal,GetUserById) - Parameters: น้อยที่สุด, ใช้ Object/Record แทนหลาย Parameter
- Return: หลีกเลี่ยง null สำหรับ Collection (คืน Empty Array/List)
- Expression-bodied:
public int Add(int a, int b) => a + b; - Async Suffix:
Task<T> GetDataAsync()
Method Overloading vs Optional Parameters
// Overloading
void Process(int x) { ... }
void Process(int x, int y) { ... }
// Optional Parameters (Cleaner)
void Process(int x, int y = 10, string mode = "default") { ... }
// เรียก: Process(1), Process(1, 2), Process(1, 2, "fast")
Local Functions (C# 7.0+)
ประกาศ Method ภายใน Method อื่น (Encapsulation, Capture Variables)
public void OuterMethod()
{
int factor = 2;
int InnerMultiply(int x) => x * factor; // Local Function
Console.WriteLine(InnerMultiply(5)); // 10
}