C# picks the right method based on parameters you pass.
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
static int Add(int a, int b, int c) => a + b + c;
Console.WriteLine(Add(2, 3)); // 5 - calls int version
Console.WriteLine(Add(2.5, 3.1)); // 5.6 - calls double
Console.WriteLine(Add(1, 2, 3)); // 6 - calls 3-param
static void Increment(ref int x) { x++; } // ref: must be initialized
int num = 5;
Increment(ref num); // num is now 6
static bool TryParse(string s, out int result) {
return int.TryParse(s, out result); // out: must assign before return
}
if (int.TryParse("123", out int val)) {
Console.WriteLine(val); // 123
}
Expression-Bodied Methods: Short Syntax
static int Square(int x) => x * x; // Same as { return x * x; }
static bool IsEven(int x) => x % 2 == 0;
static void Print(string msg) => Console.WriteLine(msg);
Real Example: Razorpay Payment Method
static bool ProcessPayment(decimal amount, string cardNumber, out string txnId) {
txnId = Guid.NewGuid().ToString();
if (amount <= 0) throw new ArgumentException("Amount must be positive");
if (string.IsNullOrEmpty(cardNumber)) throw new ArgumentNullException("Card required");
// Call payment gateway API here
Console.WriteLine($"Charged โน{amount}. TxnID: {txnId}");
return true;
}
if (ProcessPayment(500m, "1234-5678", out string id)) {
Console.WriteLine($"Success! ID: {id}");
}
Gotcha #1: Method with void return can't be assigned: var x = Print(); fails Gotcha #2:out param MUST be assigned in method. ref must be initialized before calling Gotcha #3: Optional params must be last: (string a, int b = 0) OK. (int b = 0, string a) Error
Quick Check ๐ง
EasyQ1: What keyword sends a value back from method?
MediumQ1: Can 2 methods have same name in same class?
HardQ2: What's wrong with this? static void Test(out int x) { if(false) x=5; }
HardQ3: Output? int n=5; Inc(ref n); void Inc(ref int x){x++;} Console.Write(n);
No comments yet. Be the first to share your thoughts!