Definition
In C#, a struct (short for structure) is a value type used to encapsulate related data and behavior into a single, lightweight object. Structs are often used when you need to represent simple data objects that do not require the overhead of a class.
Key Features of Structs
- Value Type:
- Structs are stored on the stack, unlike classes, which are reference types and stored on the heap.
- When a struct is assigned to a new variable, a copy of the value is created, not a reference.
- Lightweight:
- Designed for scenarios where you need small data objects that are allocated and deallocated quickly.
- No Inheritance:
- A struct cannot inherit from another struct or class.
- However, a struct can implement interfaces.
- Default Constructor:
- Structs do not allow explicit parameterless constructors.
- The compiler provides a default constructor that initializes all fields to their default values (e.g.,
0
for integers,false
for booleans).
- Immutability (Recommended):
- While structs can have mutable fields, it’s recommended to design structs as immutable for better performance and consistency.
Declaring a Struct
Here’s an example of defining and using a struct:
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
// Constructor to initialize the fields
public Point(int x, int y)
{
X = x;
Y = y;
}
// Method to calculate the distance from another point
public double DistanceTo(Point other)
{
return Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
}
}
// Usage
class Program
{
static void Main()
{
Point p1 = new Point(3, 4);
Point p2 = new Point(0, 0);
Console.WriteLine($"Distance: {p1.DistanceTo(p2)}"); // Output: Distance: 5
}
}
Differences Between Structs and Classes
Feature | Struct | Class |
---|---|---|
Type | Value type | Reference type |
Memory Allocation | Stored on the stack | Stored on the heap |
Inheritance | Cannot inherit other types | Can inherit from classes |
Default Constructor | Compiler-provided | User-defined allowed |
Performance | Faster for small objects | More suitable for large, complex objects |
Nullability | Cannot be null unless wrapped in Nullable<T> | Can be null |
When to Use a Struct
Use a struct when:
- You need a small, simple data object.
- The object is immutable (values don’t change after creation).
- You care about performance and want to avoid heap allocations.
- You don’t need inheritance.
Example scenarios:
- Representing points, colors, or complex numbers.
- Simple containers like
KeyValuePair
orTuple
.
Common Examples in .NET
C# and .NET use structs for several built-in types:
- Primitive types like
int
,float
,double
,bool
. System.DateTime
for dates and times.System.TimeSpan
for time intervals.System.Guid
for globally unique identifiers.
Structs are efficient and powerful for specific use cases where simplicity and performance are critical.