Skip to content

struct

Context: A struct is a value type that can encapsulate data and behavior. Unlike classes, structs do not support inheritance.

public struct Rectangle
{
public double Width;
public double Height;
public double Area() => Width * Height;
}

A struct can have parameterized constructors. The parameterless constructor is not allowed (C# 10+ allows it under certain conditions).

public struct Color
{
public byte R, G, B;
public Color(byte r, byte g, byte b) => (R, G, B) = (r, g, b);
}

High‑performance numeric types: Use structs for complex numbers, fractions, or money amounts to reduce heap allocations in tight loops.

Example: In .NET, System.Decimal is a struct. It provides arithmetic operations with value semantics.