← Back to Tutorials Chapter 4

Methods

Defining Methods

Methods are reusable blocks of code that perform specific tasks.

static int Add(int a, int b) {
    return a + b;
}

static void Greet(string name) {
    Console.WriteLine($"Hello, {name}!");
}

// Calling methods
int sum = Add(5, 3);
Greet("Alice");

Parameters - ref, out, in

// ref - must be initialized before passing
void Double(ref int num) { num *= 2; }
int value = 5;
Double(ref value);  // value becomes 10

// out - must be assigned inside the method
void TryParse(string s, out int result) {
    result = int.TryParse(s, out int r) ? r : 0;
}

// in - read-only reference
void Display(in int num) {
    Console.WriteLine(num);
}

Method Overloading

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;

Expression-Bodied Members

static int Square(int x) => x * x;
static void Print(string msg) => Console.WriteLine(msg);
C# methods diagram

Practice Task

Write a C# program that applies the concepts covered in this chapter. Experiment with different inputs and test your understanding.