C# Tutorial · Control Flow · Lesson 11 of 22

C# Methods

Define methods with parameters, defaults, named arguments, out/ref and overloading.

Methods

Methods live in classes. Here a static class groups them (top-level programs can also declare local functions, but those can't be overloaded):

Example 1
Console.WriteLine(Calc.Add(2, 3) + " " + Calc.Add(1.5, 2.25));
Console.WriteLine(Calc.Greet("Ada") + " " + Calc.Greet(greeting: "Hi", name: "Lin"));
Console.WriteLine(Calc.Sum() + " " + Calc.Sum(1, 2, 3));
Calc.MinMax(new[] { 4, 9, 1 }, out int lo, out int hi);
Console.WriteLine($"{lo}..{hi}");
int n = 21;
Calc.Double(ref n);
Console.WriteLine(n);

static class Calc
{
    public static int Add(int a, int b) => a + b;
    public static double Add(double a, double b) => a + b;   // overload
    public static string Greet(string name, string greeting = "Hello") => $"{greeting}, {name}!";
    public static int Sum(params int[] values) => values.Sum();
    public static void MinMax(int[] values, out int min, out int max) { min = values.Min(); max = values.Max(); }
    public static void Double(ref int x) => x *= 2;
}

Output

5 3.75
Hello, Ada! Hi, Lin!
0 6
1..9
42

Run this on your computer — see “Get Started” for setup.

Parameters

  • Optional parameters have defaults; callers can use named arguments.
  • params int[] values accepts any number of arguments.
  • out returns extra values (int.TryParse); ref passes a variable by reference.
  • Expression-bodied members: int Square(int x) => x * x;

Test yourself

Which keyword lets a method return an extra value through a parameter?

  1. return
  2. out
  3. params
  4. yield
Show answer

Answer: out