Classes
C# Structs
Defining Structs
C# structs are value types for lightweight data.
Introduction to Structs in C#
In C#, a struct is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of a point in 3D space. Structs are ideal for lightweight data storage since they are allocated on the stack rather than the heap, which often results in increased performance, especially within tight loops or frequently called methods.
Defining a Struct
Defining a struct in C# is straightforward. You use the struct
keyword followed by the struct name and a pair of curly braces. Inside, you can define fields, properties, and methods, similar to a class.
Key Characteristics of Structs
- Value Type: Structs are value types, meaning they hold their data directly rather than through a reference.
- Immutability: While structs can be mutable, it's a best practice to make them immutable for consistency.
- No Inheritance: Structs do not support inheritance but can implement interfaces.
- Default Constructor: A parameterless constructor cannot be defined in a struct. The compiler provides a default constructor that initializes all fields to their default values.
Using Structs in C#
Structs are used similarly to classes in C#. You can create an instance of a struct using the new
keyword or by simply declaring a variable of the struct type. Here's how you can use the Point
struct defined earlier:
When to Use Structs
Structs are particularly useful when you need a small data structure that does not require the overhead of heap allocation. Consider using structs when:
- The data structure is small and simple.
- The structure will not be modified after creation (i.e., it can be immutable).
- Performance is critical, and you want to avoid the garbage collector.