8️⃣ C# Object-Oriented Programming (OOP)
Estimated reading: 3 minutes 276 views

C# Structures – Lightweight Value Types for Efficient Data Handling


Introduction – Why Use Structures in C#?

In performance-critical applications or when dealing with small data entities like points, coordinates, or pixels, using classes may add unnecessary memory overhead. That’s where structures (structs) come in. In C#, struct provides a way to create lightweight, value-type objects with similar capabilities to classesβ€”but with better memory efficiency.

In this guide, you’ll learn:

  • What structures are and how they differ from classes
  • How to define and use a struct
  • Struct limitations and use cases
  • Performance implications of structs vs classes

Core Concept – What is a Structure in C#?

A structure (struct) is a value type in C# used to define small, simple objects. Unlike classes (which are reference types), structs are allocated on the stack, making them faster and more efficient in certain contexts.


Struct Syntax:

struct Point
{
    public int X;
    public int Y;

    public void Print() => Console.WriteLine($"({X}, {Y})");
}

Structs can contain:

  • Fields
  • Properties
  • Methods
  • Constructors (with parameters only)
  • Operators and events

Code Example – Using a Struct

Point p = new Point { X = 10, Y = 20 };
p.Print(); // Output: (10, 20)

Explanation:

  • The Point struct is initialized using object initializer syntax.
  • The Print() method displays its values.

Struct vs Class – Key Differences

FeatureStructClass
TypeValue TypeReference Type
AllocationStackHeap
InheritanceCannot inherit from another struct/classCan inherit from another class
Default ConstructorNot allowedAllowed
NullabilityCannot be null (unless nullable)Can be null
PerformanceMore efficient for small objectsSlower due to heap allocation

Limitations of Structs

  • Cannot inherit from another struct or class
  • Cannot declare a parameterless constructor (except from C# 10+ with record struct)
  • Cannot initialize fields directly (must use constructor or initializer)
  • Must be used carefully to avoid boxing when used in interfaces or collections

Example – Immutable Struct

readonly struct Currency
{
    public decimal Amount { get; }
    public string Code { get; }

    public Currency(decimal amount, string code)
    {
        Amount = amount;
        Code = code;
    }
}

Use Case: Immutable value objects like Currency, Point, Rectangle.


Best Practices & Tips

Tip: Use readonly struct for immutable, efficient value types.

Pitfall: Avoid using large structs or frequently modifying struct membersβ€”they may lead to performance issues.

Best Practice: Prefer structs for small, short-lived data and frequently created objects.


Real-World Use Cases

  • Geometry and coordinates (Point, Vector)
  • Lightweight data models (e.g., Currency, DateRange)
  • Game development physics calculations
  • Custom value objects in high-performance systems
  • Efficient iterations in large collections

Summary – Recap & Next Steps

Key Takeaways:

  • Structs are value typesβ€”allocated on the stack.
  • Use them for small, immutable, performance-sensitive objects.
  • Unlike classes, structs cannot inherit and are not nullable (unless wrapped with ?).

Real-world relevance: Ideal for low-memory, high-speed scenarios like graphics, games, and microservices.


FAQ Section

When should I use a struct instead of a class?
Use structs when the object is small, immutable, and used in high-frequency operations.


Can I assign a struct to null?
Not directly. But you can use Nullable<T> or Point? syntax:

Point? p = null;

Can a struct have methods and properties?
Yes! Structs can include methods, properties, fields, and constructors (except parameterless).


Are structs copied or referenced when passed to methods?
Structs are copied by value unless passed with ref or in.


What is a readonly struct?
A readonly struct ensures that all fields are immutable, and no modifications can occur after construction.


Share Now :
Share

πŸ—οΈ C# Structures

Or Copy Link

CONTENTS
Scroll to Top