C#C# · Lesson 4 of 9

Methods & Properties

In C#, properties are special class members that look like fields but act like methods. They're how you do encapsulation without writing getBlah()/setBlah() everywhere.

C#
// Methods
int Add(int a, int b) => a + b;   // expression-bodied (C# 6+)

string Greet(string name, string title = "friend") {
    return $"Hello, {title} {name}!";
}

// Out parameters
bool TryDivide(double a, double b, out double result) {
    if (b == 0) { result = 0; return false; }
    result = a / b;
    return true;
}

// Params — variable arguments
int Sum(params int[] numbers) {
    int total = 0;
    foreach (int n in numbers) total += n;
    return total;
}

// Extension methods — add methods to existing types
static class StringExtensions {
    public static string Capitalize(this string s) {
        if (string.IsNullOrEmpty(s)) return s;
        return char.ToUpper(s[0]) + s[1..];
    }
}

// Usage:
Console.WriteLine(Add(3, 4));             // 7
Console.WriteLine(Greet("Alice"));        // Hello, friend Alice!
Console.WriteLine(Greet("Smith", "Dr.")); // Hello, Dr. Smith!

if (TryDivide(10, 3, out double r)) {
    Console.WriteLine($"{r:F4}");  // 3.3333
}

Console.WriteLine(Sum(1, 2, 3, 4, 5));   // 15
Console.WriteLine("hello".Capitalize());  // Hello
C#
class Temperature {
    private double celsius;

    // Auto-property (no backing field needed)
    public string Unit { get; set; } = "Celsius";

    // Property with getter and setter
    public double Celsius {
        get => celsius;
        set {
            if (value < -273.15)
                throw new ArgumentOutOfRangeException("Below absolute zero!");
            celsius = value;
        }
    }

    // Computed property (getter only)
    public double Fahrenheit => celsius * 9 / 5 + 32;
    public double Kelvin => celsius + 273.15;

    public Temperature(double celsius) {
        Celsius = celsius;
    }

    public override string ToString() =>
        $"{Celsius}°C / {Fahrenheit:F1}°F / {Kelvin:F1}K";
}

var t = new Temperature(100);
Console.WriteLine(t);           // 100°C / 212.0°F / 373.1K
Console.WriteLine(t.Fahrenheit); // 212
t.Celsius = 0;
Console.WriteLine(t.Kelvin);     // 273.15