Immutable C# Structs

This is a basic immutable struct in C#.

public struct PuppyDogPair
{
    public PuppyDogPair(Guid puppyId, Guid dogId)
        : this()
    {
        Puppy = puppyId;
        Dog = dogId;
    }
    
    public Guid Puppy { get; private set; }
    public Guid Dog { get; private set; }
}

If your struct is not immutable, then you will have to pass it by reference if you want to mutate it inside helper methods.

private static void PerformAction(ref Config config)
{
    // do something with config
    config.usages++;
}

One great way of using immutable structs is to fill existing result rows with additional information. This code iterates over a result enumerable and keys into an existing dictionary to fill it with more information:

// Get data from database
foreach (var row in rowResults)
{
    var lookupPair = new PuppyDogPair(row.puppyId, row.dogId);
    
    gridRow = gridRowDictionary[lookupPair];
    gridRow.BirthDay = row.BirthDay
    // ... push more results into grid row from row
}
csharp 

See also