Methods
Methods
Section titled βMethodsβWhat it means
Section titled βWhat it meansβA method is a named, reusable block of code that belongs to a class. It has a return type (or void for no return value), a name, and a parameter list. Methods can be overloaded (multiple methods with the same name but different parameter lists), and parameters can have default values, be optional, or accept a variable number of arguments (params).
Examples
Section titled βExamplesβpublic class Calculator{ public int Add(int a, int b) => a + b;
// Overloading: same name, different parameter types/counts public double Add(double a, double b) => a + b; public int Add(int a, int b, int c) => a + b + c;
// Default parameter value public int Multiply(int a, int b = 2) => a * b;
// params -- accepts any number of arguments public int Sum(params int[] numbers) => numbers.Sum();}
var calc = new Calculator();calc.Add(1, 2); // 3 -- int overloadcalc.Add(1.5, 2.5); // 4.0 -- double overloadcalc.Multiply(5); // 10 -- uses default b = 2calc.Sum(1, 2, 3, 4); // 10Common mistake
Section titled βCommon mistakeβPassing a reference-type argument and assuming the method canβt affect the callerβs object β reference types are passed by reference to the object, so mutating the objectβs members inside the method does affect the caller, even though C# passes the reference itself by value.
public class Counter { public int Value; }
void Reset(Counter c){ c.Value = 0; // mutates the SAME object the caller has c = new Counter(); // this reassignment does NOT affect the caller's variable}
var counter = new Counter { Value = 5 };Reset(counter);Console.WriteLine(counter.Value); // 0 -- the mutation was visible to the callerQuick practice
Section titled βQuick practiceβ-
What is method overloading?
Answer
Defining multiple methods with the same name but different parameter types, counts, or order β the compiler picks the right one based on the arguments you pass. -
What does the
paramskeyword let a method accept?Answer
A variable number of arguments of the same type, passed either as individual arguments or as an array β e.g.Sum(1, 2, 3)orSum(new[] {1, 2, 3}). -
If a method modifies a property on a reference-type parameter, does the caller see that change?
Answer
Yes β reference types pass a reference to the same underlying object, so mutations to its members are visible to the caller (though reassigning the parameter itself to a new object is not).