Methods and parameters

C# · Essentials · 12 min

Methods are the unit of reuse; their parameter features shape how readable your call sites are.

A method declares a return type (or void), a name and typed parameters: static int Add(int a, int b) => a + b;. The => form is an expression-bodied member for one-expression methods; otherwise use a { } block with return.

In a top-level program you can declare local functions right among the statements; in classes, methods are members, static when they don't need an instance.

Parameter features:

  • Optional parameters have defaults: void Greet(string name, string greeting = "Hello").
  • Named arguments make calls readable and let you skip optionals: Greet("Ada", greeting: "Hi").
  • params int[] values (or params ReadOnlySpan<int> / collections in C# 13+) accepts any number of arguments.
  • out parameters return extra values: the TryParse pattern bool TryX(string s, out int result).
  • ref passes a variable by reference so the method can change it; in passes by read-only reference.

By default arguments are passed by value: the method gets a copy of the value. For reference types such as classes and arrays, the copy is of the reference, so the method can mutate the object but not make the caller's variable point elsewhere.

Overloading allows several methods with the same name and different parameter lists. To return several values, prefer a tuple (int min, int max) or a record over many out parameters.

Example

static int Add(int a, int b) => a + b;

static string Greet(string name, string greeting = "Hello")
    => $"{greeting}, {name}!";

static int Sum(params int[] values)
{
    int total = 0;
    foreach (var v in values) total += v;
    return total;
}

static (int Min, int Max) Range(int[] xs) => (xs.Min(), xs.Max());

static void Double(ref int x) => x *= 2;

Console.WriteLine(Add(2, 3));                 // 5
Console.WriteLine(Greet("Ada"));              // Hello, Ada!
Console.WriteLine(Greet("Ada", greeting: "Hi")); // Hi, Ada!
Console.WriteLine(Sum(1, 2, 3, 4));           // 10
var (lo, hi) = Range([4, 9, 1]);
Console.WriteLine($"{lo}..{hi}");             // 1..9
int n = 5; Double(ref n);
Console.WriteLine(n);                         // 10

Remember

  • => gives one-line expression-bodied methods
  • Optional + named arguments keep call sites readable
  • Arguments are passed by value; ref/out pass the variable itself
  • Return tuples instead of many out parameters

Check yourself

  1. A method void Reset(int[] a) { a = new int[3]; } is called as Reset(arr). What happens to arr?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods