What is struct in C#: Definition and Usage
struct in C# is a value type that stores related data together in a single unit. Unlike classes, structs are usually stored on the stack and are best for small, simple data containers.How It Works
A struct in C# is like a small box that holds a few pieces of related information together. Imagine you have a box for a point on a map that holds two numbers: the X and Y coordinates. This box keeps those numbers close and easy to access.
Unlike classes, which are stored on the heap and accessed by reference (like a remote control pointing to a TV), structs are usually stored directly where they are used (like having the TV right in front of you). This means structs are faster for small data because they don’t need extra steps to find the data.
Structs are best when you want to group a few simple values and don’t need the extra features of classes, like inheritance or complex behavior.
Example
This example shows a struct named Point that holds two numbers. We create a point and print its values.
using System;
struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
}
class Program
{
static void Main()
{
Point p = new Point(3, 4);
Console.WriteLine($"Point coordinates: X = {p.X}, Y = {p.Y}");
}
}When to Use
Use structs when you need to store small, simple groups of data that don’t change much. For example, points in 2D space, colors with red/green/blue values, or a date with day/month/year.
Structs are good when you want fast access and low memory overhead. Avoid structs if your data needs to be large, change often, or use inheritance and polymorphism, which are features of classes.
Key Points
- Structs are value types usually stored on the stack.
- They are best for small, simple data containers.
- Structs do not support inheritance.
- Use structs for performance when data size is small.
- Classes are better for complex data and behavior.