In C#, structs are value types that allow you to encapsulate related data and functionality into a single unit. They provide a lightweight alternative to classes for simple data structures.
Structs are user-defined types that group variables of different data types under a single name. Unlike classes, which are reference types, structs are value types. This means they are stored on the stack rather than the heap, making them more efficient for small, simple data structures.
To declare a struct in C#, use the struct
keyword followed by the struct name. Here's a basic example:
public struct Point
{
public int X;
public int Y;
}
You can create and use struct instances similarly to how you work with classes. Here's an example:
Point p1 = new Point();
p1.X = 10;
p1.Y = 20;
// Or initialize with an object initializer
Point p2 = new Point { X = 30, Y = 40 };
Structs can have constructors, but they must initialize all fields. The default parameterless constructor is always provided and cannot be redefined.
public struct Rectangle
{
public double Width;
public double Height;
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
}
You can define methods within structs to operate on their data. This encapsulation helps keep related functionality together.
public struct Circle
{
public double Radius;
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
While structs and classes share similarities, they have key differences:
To deepen your understanding of C# structs and related topics, explore these concepts:
By mastering structs, you'll have a powerful tool for creating efficient, lightweight data structures in your C# programs.