๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 4 of 40
Lesson 4 of 40 Foundations Beginner โฑ 25 min

Methods, Parameters & Return Types

Write reusable, well-structured methods โ€” learn optional parameters, named arguments, ref/out/in, local functions, and method overloading.

Part 1: Defining and Calling Methods

// Simple method
static int Add(int a, int b) => a + b; // Expression-bodied

// Multi-statement method
static string FormatName(string first, string last)
{
    if (string.IsNullOrEmpty(first)) throw new ArgumentException("First name required");
    return $"{last}, {first}";
}

Part 2: Optional & Named Parameters

static void PrintReport(string title, int pageSize = 20, bool sorted = true)
{
    Console.WriteLine($"{title}: {pageSize} rows, sorted={sorted}");
}

// Named arguments โ€” order doesn't matter
PrintReport("Sales", sorted: false);
PrintReport(title: "Orders", pageSize: 50);

Part 3: ref, out and in Parameters

// out โ€” method sets the value
bool ok = int.TryParse("42", out int result);

// ref โ€” pass by reference (read & write)
static void Double(ref int value) => value *= 2;
int x = 5; Double(ref x); // x is now 10

// in โ€” read-only ref (no copying large structs)
static double Magnitude(in Vector3 v) => Math.Sqrt(v.X*v.X + v.Y*v.Y);

Part 4: Local Functions & Method Overloading

// Local function โ€” scoped to containing method
static int Fibonacci(int n)
{
    if (n <= 1) return n;
    return Fib(n - 1) + Fib(n - 2);
    static int Fib(int n) => n <= 1 ? n : Fib(n-1) + Fib(n-2);
}
Overloading lets multiple methods share a name with different signatures โ€” the compiler picks the right one by argument types.

C# in Visual Studio 2026

๐Ÿ“˜ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition