C# Course

C# Methods (Functions)

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Defining Methods

using System;

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

    static double CircleArea(double r) {
        return Math.PI * r * r;
    }

    static void Main() {
        Console.WriteLine(Add(3, 4));           // 7
        Console.WriteLine(CircleArea(5.0));     // 78.539...
    }
}

Expression-Bodied Methods (C# 6+)

static int Square(int x) => x * x;
static string Greet(string name) => $"Hello, {name}!";

Console.WriteLine(Square(5));      // 25
Console.WriteLine(Greet("Alice")); // Hello, Alice!

Optional and Named Parameters

static void PrintInfo(string name, int age = 18, string country = "US") {
    Console.WriteLine($"{name}, {age}, {country}");
}
PrintInfo("Alice");                     // Alice, 18, US
PrintInfo("Bob", 25);                   // Bob, 25, US
PrintInfo("Carol", country: "UK");      // Carol, 18, UK

Method Overloading

static int Multiply(int a, int b) => a * b;
static double Multiply(double a, double b) => a * b;
static int Multiply(int a, int b, int c) => a * b * c;

Multiply(2, 3);         // 6
Multiply(2.5, 3.0);     // 7.5
Multiply(2, 3, 4);      // 24

Recursion

static int Factorial(int n) {
    if (n <= 1) return 1;
    return n * Factorial(n - 1);
}
Console.WriteLine(Factorial(5)); // 120

out and ref Parameters

static void Divide(int a, int b, out int quotient, out int remainder) {
    quotient = a / b;
    remainder = a % b;
}
Divide(17, 5, out int q, out int r);
Console.WriteLine($"{q} remainder {r}"); // 3 remainder 2