Structs in C#

Typed collections or fields in a target language

In this example, we’ll cover how to work with typed collections of fields, typically known as structs. Structs are useful for grouping data together to form records.

This Person struct type in C# has Name and Age fields.

using System;

public struct Person
{
    public string Name;
    public int Age;

    public Person(string name)
    {
        Name = name;
        Age = 42; // Default age
    }
}

class Program
{
    static void Main()
    {
        // Creating a new struct
        Console.WriteLine(new Person { Name = "Bob", Age = 20 });

        // Naming fields when initializing a struct
        Console.WriteLine(new Person { Name = "Alice", Age = 30 });

        // Omitted fields will be zero-valued
        Console.WriteLine(new Person { Name = "Fred" });

        // An & prefix yields a pointer to the struct
        Person ann = new Person { Name = "Ann", Age = 40 };
        Console.WriteLine(ann);

        // It's idiomatic to encapsulate new struct creation in constructor functions
        Console.WriteLine(new Person("Jon"));

        // Access struct fields with a dot
        Person sean = new Person { Name = "Sean", Age = 50 };
        Console.WriteLine(sean.Name);

        // You can also use dots with struct references
        Person sp = sean;
        Console.WriteLine(sp.Age);

        // Structs are mutable
        sp.Age = 51;
        Console.WriteLine(sp.Age);

        // Example of an anonymous struct for table-driven tests
        var dog = new { Name = "Rex", IsGood = true };
        Console.WriteLine(dog);
    }
}

To run the program, simply compile and execute it using the C# compiler:

$ csc Program.cs
$ Program
Person { Name = Bob, Age = 20 }
Person { Name = Alice, Age = 30 }
Person { Name = Fred, Age = 0 }
Person { Name = Ann, Age = 40 }
Person { Name = Jon, Age = 42 }
Sean
50
51
{ Name = Rex, IsGood = True }

Now that we can run and build basic C# programs, let’s learn more about the language.