C# Composite Types

Composite types group data and behavior: struct (value), class (reference), record, and collections such as arrays and generics.

Struct

Definition

A struct is a value type combining fields and methods. Prefer small, immutable data carriers.

struct Point
{
    public double X;
    public double Y;
}

Usage & Copies

Assigning a struct copies the data. Changes to the copy do not affect the original.

Point a = new Point { X = 1, Y = 2 };
Point b = a;   // full copy
b.X = 99;      // a.X stays 1

Class

Definition

A class is a reference type. Members: fields, properties, methods, events.

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Objects & References

Instances are created with new. Assigning a class variable copies the reference, not the object.

Person p1 = new Person { Name = "Ada", Age = 36 };
Person p2 = p1;   // same object
p2.Age = 40;      // p1.Age is also 40

Record

Value Semantics

A record is a reference type with built-in value equality. Two records are equal when their data is equal.

record Point(double X, double Y);

var p = new Point(1, 2);
var q = new Point(1, 2);
Console.WriteLine(p == q); // True — value equality

Example

Records support non-destructive updates: with produces a new copy, the original stays unchanged.

record Person(string Name, int Age);

var alice = new Person("Alice", 30);
var older = alice with { Age = 31 }; // non-destructive copy
Console.WriteLine(older); // Person { Name = Alice, Age = 31 }

Arrays & Collections

Arrays

Fixed-size, zero-based indexed storage of one element type.

int[] nums = { 1, 2, 3 };
Console.WriteLine(nums[0]); // 1
nums[2] = 9;

List<T>

Generic, resizable list — the default collection for ordered data.

var names = new List<string> { "Ada", "Linus" };
names.Add("Grace");
Console.WriteLine(names.Count); // 3
Console.WriteLine(names[0]);    // Ada

Dictionary<TKey, TValue>

Key-value store with fast lookup by key.

var scores = new Dictionary<string, int>
{
    ["Ada"] = 100,
    ["Linus"] = 90
};
Console.WriteLine(scores["Ada"]); // 100