Value vs Reference Types: ref gotcha

CSharp · Console

/Program.cs

using System;

public class Person
{
    public string Name;
    public Person(string name) => Name = name;
}

public class Program
{
    static void TryDouble(int number)
    {
        number = number * 2;
    }

    static void Rename(Person person)
    {
        person.Name = "Renamed";
    }

    static void Replace(Person person)
    {
        person = new Person("Bob");
    }

    static void ReplaceRef(ref Person person)
    {
        person = new Person("Bob");
    }

    public static void Main()
    {
        Console.WriteLine("Example A: value type passed normally");
        int value = 10;
        TryDouble(value);
        Console.WriteLine(value);

        Console.WriteLine();
        Console.WriteLine("Example B: reference type, mutating a field");
        var b = new Person("Alice");
        Rename(b);
        Console.WriteLine(b.Name);

        Console.WriteLine();
        Console.WriteLine("Example C: reference type, reassigned with new (no ref)");
        var c = new Person("Alice");
        Replace(c);
        Console.WriteLine(c.Name);

        Console.WriteLine();
        Console.WriteLine("Example D: reference type, reassigned with new (with ref)");
        var d = new Person("Alice");
        ReplaceRef(ref d);
        Console.WriteLine(d.Name);
    }
}
;