C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Methods Introduction

C# Methods Introduction

A method is a named block of code that performs a specific task. Methods prevent code duplication and make programs easier to read and maintain.

1 - Defining a Method

// Syntax: accessModifier returnType MethodName(parameters)
public static int Add(int a, int b)
{
    return a + b;
}

// Call it
int result = Add(3, 4); // 7

2 - void Methods

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

Greet("Alice"); // Hello, Alice!

3 - Expression-Bodied Members (C# 6+)

public static int Square(int n) => n * n;
public static void Print(string s) => Console.WriteLine(s);

Console.WriteLine(Square(5)); // 25

4 - Local Functions (C# 7+)

public static int Factorial(int n)
{
    return Calculate(n);

    int Calculate(int x) => x <= 1 ? 1 : x * Calculate(x - 1);
}

Console.WriteLine(Factorial(5)); // 120

Note: In C#, every method must have a declared return type. Use void when the method returns nothing. The compiler enforces that all code paths return a value for non-void methods.

-Tip-