Welcome to Shaun Luttin's public notebook. It contains rough, practical notes. The guiding idea is that, despite what marketing tells us, there are no experts at anything. Sharing our half-baked ideas helps everyone. We're all just muddling thru. Find out more about our work at bigfont.ca.

Value types can have methods!

Tags: c#, types

void Main()
{
    var one = new ValueType();
    var two = one; 
    // two's value is now a copy of one's value
    // and both are **actual values**

    var three = new ReferenceType();
    var four = three;
    // four's value is now a copy of three's value
    // and both values **are references to the same object**

    one.Name = "one";
    two.Name = "two";
    // we changed two separate values

    three.Name = "three";
    four.Name = "four"; 
    // we are changed one object

    Console.WriteLine(one.Foo()); // one
    Console.WriteLine(two.Foo()); // two
    Console.WriteLine(three.Foo()); // four
    Console.WriteLine(four.Foo()); // four
}

public class ReferenceType
{
    public string Name;
    public string Foo()
    {
        return Name;
    }
}

public struct ValueType
{
    public string Name;
    public string Foo()
    {
        return Name;
    }
}