Start Coding

Topics

C# Structs: Efficient Value Types for Data Encapsulation

In C#, structs are value types that allow you to encapsulate related data and functionality into a single unit. They provide a lightweight alternative to classes for simple data structures.

What are Structs?

Structs are user-defined types that group variables of different data types under a single name. Unlike classes, which are reference types, structs are value types. This means they are stored on the stack rather than the heap, making them more efficient for small, simple data structures.

Declaring a Struct

To declare a struct in C#, use the struct keyword followed by the struct name. Here's a basic example:


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

Using Structs

You can create and use struct instances similarly to how you work with classes. Here's an example:


Point p1 = new Point();
p1.X = 10;
p1.Y = 20;

// Or initialize with an object initializer
Point p2 = new Point { X = 30, Y = 40 };
    

Struct Constructors

Structs can have constructors, but they must initialize all fields. The default parameterless constructor is always provided and cannot be redefined.


public struct Rectangle
{
    public double Width;
    public double Height;

    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }
}
    

Methods in Structs

You can define methods within structs to operate on their data. This encapsulation helps keep related functionality together.


public struct Circle
{
    public double Radius;

    public double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}
    

Structs vs Classes

While structs and classes share similarities, they have key differences:

  • Structs are value types, classes are reference types
  • Structs are stored on the stack, classes on the heap
  • Structs cannot inherit from other structs or classes
  • Structs cannot have a parameterless constructor
  • Structs are sealed by default

Best Practices for Using Structs

  • Use structs for small, simple data structures
  • Keep structs immutable when possible
  • Avoid using structs as parameters in frequently called methods to prevent excessive copying
  • Consider using structs when working with large arrays of simple data types

Related Concepts

To deepen your understanding of C# structs and related topics, explore these concepts:

By mastering structs, you'll have a powerful tool for creating efficient, lightweight data structures in your C# programs.