Tools
Log in
English

Learn to codeC#

C# composition and static

Based on C# 12record · C# 9+with · C# 9+

C# composition over inheritance, static classes, records and with expressions.

In one line

Composition keeps another object in a property instead of inheriting from it. static members belong to the class itself, not to objects. A record is a small type compared by value.

Why you need it

If an order inherited from an address, you would be saying "an order is an address", which is nonsense, and every new address field would ripple into orders. When an order holds an address as a property, each can change on its own.

Work that belongs to no object, like tax, and values with exactly one copy for the whole class, like the order count, fit static and are used without creating objects.

Everyday picture

Think of a lunch box. It has rice, side dishes and soup (composition); the rice is not the lunch box’s parent. The board on the shop wall showing "boxes sold today" exists once for the shop, not once per box (static). Two side dishes with the same name and price are simply the same dish (record).

Example code

Program.cs · 42 lines
var home = new Address("12 Pine St", "Busan");var order = new Order(home);order.Add(new Item("Pizza", 18_000m));order.Add(new Item("Cola", 2_000m));var office = home with { Street = "7 Harbor Rd" };var second = new Order(office);second.Add(new Item("Pizza", 18_000m));Console.WriteLine($"#{order.Number} {order.Total():N0} won to {order.To.City}");Console.WriteLine($"#{second.Number} to {second.To.Street}, same city: {office.City == home.City}");Console.WriteLine($"Same first item: {order.First == second.First}, orders: {Order.Count}"); record Address(string Street, string City);record Item(string Name, decimal Price); static class Tax{    public const decimal Rate = 0.1m;     public static decimal Add(decimal amount) => amount * (1 + Rate);} class Order{    private static int count;    private readonly List<Item> items = [];     public int Number { get; }    public Address To { get; }    public static int Count => count;    public Item First => items[0];     public Order(Address to)    {        count++;        Number = count;        To = to;    }     public void Add(Item item) => items.Add(item);     public decimal Total() => Tax.Add(items.Sum(i => i.Price));}

When to use it

  • "X has a Y" fits (an order has an address)
  • Calculations or constants with no object state (tax rate, unit conversion). Put them in a static class
  • Small data that counts as equal when the values match (address, point, amount). Use a record

When in doubt, pick composition over inheritance. A held object is easy to swap later.

A const is baked in at compile time. For settings that may change, use static readonly.

Common mistakes

Making a value-only type a class and comparing with ==

For a class, == asks whether both sides are the same object. Make it a record to compare values; the compiler writes Equals, GetHashCode and ToString for you.

Wrong

var a = new Item("Pizza", 18_000m);var b = new Item("Pizza", 18_000m);Console.WriteLine(a == b); class Item(string name, decimal price){    public string Name => name;    public decimal Price => price;}

When you run itFalse

Fixed

var a = new Item("Pizza", 18_000m);var b = new Item("Pizza", 18_000m);Console.WriteLine(a == b); record Item(string Name, decimal Price);

When you run itTrue

Creating a static class with new

A static class is a toolbox used without objects. You cannot create one; call it through the class name, as in Tax.Add(...).

Wrong

var t = new Tax();

What the C# compiler sayserror CS0712: Cannot create an instance of the static class 'Tax'

Fixed

Console.WriteLine(Tax.Add(1_000m));

When you run it1100.0

Reading an object field from a static member

A static property runs without knowing which cart it belongs to, so it cannot read the per-object items. Members that use object values should not be static.

Wrong

class Cart{    private readonly List<Item> items = [];     public static int Size => items.Count;}

What the C# compiler sayserror CS0120: An object reference is required for the non-static field, method, or property 'Cart.items'

Fixed

class Cart{    private readonly List<Item> items = [];     public int Size => items.Count;}

Check yourself

Question 1

After changing only the city with with, what is printed?

var a = new Address("1 Oak St", "Seoul");var b = a with { City = "Jeju" };Console.WriteLine($"{a.City} {b.City} {a == b}");

Show the answer

Answer: 2. Seoul Jeju False with leaves the original record as it is and makes a new one. The cities differ, so == is False.

Question 2

After creating three orders, what is Order.Count?

var a = new Address("x", "y");new Order(a);new Order(a);new Order(a);Console.WriteLine(Order.Count);

Show the answer

Answer: 2. 3 count is static, so every order shares one slot. Each creation adds 1, giving 3.

Questions people ask

How is a record different from a class?

A record compares property values with == and Equals, prints all properties in ToString, and supports with to copy it with a few changes. It suits small value types; objects with lots of behavior stay classes.

When should I write a static class?

To collect helpers and constants that need no object state, the way Math or File work. A static class cannot be instantiated or inherited.

How do I choose between const and static readonly?

const for numbers and strings that never change; static readonly for values decided at run time or that may change later. A const is copied into the calling code, so changing it means rebuilding the callers too.