Skip to content

Methods

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).

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 overload
calc.Add(1.5, 2.5); // 4.0 -- double overload
calc.Multiply(5); // 10 -- uses default b = 2
calc.Sum(1, 2, 3, 4); // 10

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 caller
  1. What is method overloading?

    AnswerDefining 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.
  2. What does the params keyword let a method accept?

    AnswerA variable number of arguments of the same type, passed either as individual arguments or as an array β€” e.g. Sum(1, 2, 3) or Sum(new[] {1, 2, 3}).
  3. If a method modifies a property on a reference-type parameter, does the caller see that change?

    AnswerYes β€” 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).