Introduction
C# structs are value types that encapsulate a single data item. They offer several benefits, including better performance, increased code readability, and reduced memory consumption compared to classes in many cases.
They are created using the `struct` keyword. They cannot be inherited and are immutable by default, helping to prevent accidental modification.
Attributes
Structs can have various attributes, allowing you to customize their behavior and properties. Common attributes include:
- `Name` (required)
- `Data` (optional)
- `Type` (optional)
- `Size` (optional)
- `Constructor` (optional)
- `Destructor` (optional)
Usage
You can use structs in various scenarios:
- Storing small, self-contained data units.
- Creating data structures with limited scope.
- Optimizing performance by avoiding object creation overhead.
Here's a simple example:
struct Point {
int x;
int y;
}
This struct defines a point in 2D space.