Structs in C#
Structs in C# are value types that are used to encapsulate small groups of related variables. They are an essential part of the language and provide a lightweight alternative to classes. This article delves into the use of structs, comparing them with classes and records, and provides guidelines on when and how to use them effectively.
C# Struct vs Class
The primary difference between a struct (value type) and a class (reference type) in C# is how they are stored in memory. Structs are stored on the stack, which allows for quicker access but means they are best used for small data structures. Classes are stored on the heap, which can handle larger data sizes and supports inheritance, unlike structs.
Structs in C# with Examples
Structs are often used to represent simple data structures. Here's an example of a struct in C#:
public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
}
This Point struct can then be used as follows:
Point p = new Point(1, 2);
Console.WriteLine($"Point coordinates: ({p.X}, {p.Y})");
C# Struct Constructor
Structs in C# can have constructors, but unlike classes, every struct constructor must assign a value to all fields before the constructor completes. This ensures the struct is fully initialized:
public struct Color
{
public byte Red, Green, Blue;
public Color(byte red, byte green, byte blue)
{
Red = red;
Green = green;
Blue = blue;
}
}
C# Struct Initialization
Structs can be initialized without a constructor by directly setting their fields if those fields are public. However, using constructors is a more robust way of ensuring that all fields are correctly initialized.
Color c;
c.Red = 255;
c.Green = 0;
c.Blue = 0;
C# Struct vs Record
Introduced in C# 9, records are reference types that are primarily intended for immutable data structures. Unlike structs, records provide built-in functionality for value-based equality checks and with-expressions for non-destructive mutation. Structs, being value types, are suited for small and frequently created data items.
C# When to Use Struct
Structs should be used when you need a type that acts like a primitive, is small, and you have a lot of them, making the overhead of managing them on the heap (as would be the case with classes) impractical. They are ideal for high-performance scenarios where memory footprint and speed are critical.
C# Struct Default Values
When a struct is instantiated, all numeric fields are set to zero by default, and all Boolean fields are set to false. If the struct contains reference type fields, they are initialized to null.
Structs in C# are a powerful feature for creating performant and memory-efficient applications. They are particularly useful in systems where high speed and low memory usage are critical, such as in gaming or real-time systems.