SyntaxStudy
Sign Up
C# Static Members, Enums, and Records
C# Beginner 1 min read

Static Members, Enums, and Records

Static members belong to the type itself rather than any instance. A static class can only contain static members and cannot be instantiated — useful for utility functions like `Math` and `File`. Static constructors run once, before the first use of the type, and are used for one-time initialisation. Enums map a set of named constants to integer values. Marking an enum with `[Flags]` and powers-of-two values lets you combine members with bitwise OR to represent sets of options. Enums are value types and integrate well with switch expressions and pattern matching. Records (C# 9) are reference types with value-based equality semantics, built-in `ToString` formatting, and deconstruction support. `record struct` (C# 10) provides the same features as a value type. Records are ideal for DTOs, domain events, and any type where identity is determined by content rather than object reference.
Example
// Static classes, enums with Flags, and records

// Static utility class
public static class StringExtensions
{
    public static string Truncate(this string s, int maxLength) =>
        s.Length <= maxLength ? s : s[..maxLength] + "...";

    public static bool IsPalindrome(this string s)
    {
        var clean = s.ToLower().Where(char.IsLetterOrDigit).ToArray();
        return clean.SequenceEqual(clean.Reverse());
    }
}

Console.WriteLine("Hello, World!".Truncate(5));     // Hello...
Console.WriteLine("racecar".IsPalindrome());         // True

// Flags enum — combine with |
[Flags]
public enum Permissions { None = 0, Read = 1, Write = 2, Delete = 4 }

var userPerms = Permissions.Read | Permissions.Write;
Console.WriteLine(userPerms);                         // Read, Write
Console.WriteLine(userPerms.HasFlag(Permissions.Delete)); // False

// Record (reference type, value equality)
public record OrderLine(string Sku, int Quantity, decimal UnitPrice)
{
    public decimal Total => Quantity * UnitPrice;
}

var line1 = new OrderLine("ABC-001", 2, 9.99m);
var line2 = new OrderLine("ABC-001", 2, 9.99m);
Console.WriteLine(line1 == line2);   // True (value equality)
Console.WriteLine(line1.Total);      // 19.98

// Non-destructive mutation with 'with'
var line3 = line1 with { Quantity = 5 };
Console.WriteLine(line3);  // OrderLine { Sku = ABC-001, Quantity = 5, UnitPrice = 9.99 }

// Deconstruct record
var (sku, qty, price) = line1;
Console.WriteLine($"{sku}: {qty} @ ${price}");