C# Structs
Structs
A struct groups related values together, like a small class.
For example, a point on the screen has an X position and a Y position. The two values belong together, so you can put them in a struct.
To create a struct, use the struct keyword:
Example
struct Point
{
public int X;
public int Y;
}
class Program
{
static void Main(string[] args)
{
Point p = new Point();
p.X = 10;
p.Y = 20;
Console.WriteLine("X: " + p.X + ", Y: " + p.Y);
}
}
You create and use a struct just like an object of a class: with new, and with the dot syntax (p.X).
Like a class, a struct can have a constructor, so you can set the values in one line:
Example
struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
}
class Program
{
static void Main(string[] args)
{
Point p = new Point(10, 20);
Console.WriteLine("X: " + p.X + ", Y: " + p.Y);
}
}
Struct vs. Class
The big difference between a struct and a class is what happens when you assign it to another variable.
A struct is copied. The new variable gets its own copy of all the values, so a change to the copy does not change the original:
Example
struct Point
{
public int X;
public int Y;
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point();
p1.X = 10;
p1.Y = 20;
Point p2 = p1;
p2.X = 50;
Console.WriteLine("p1: " + p1.X + ", " + p1.Y);
Console.WriteLine("p2: " + p2.X + ", " + p2.Y);
}
}
p1.X is still 10. Only the copy p2 changed to 50.
A class object is shared. Here is the same code, but Point is now a class. Both variables refer to the same object, so a change through p2 also changes p1:
Example
class Point
{
public int X;
public int Y;
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point();
p1.X = 10;
p1.Y = 20;
Point p2 = p1;
p2.X = 50;
Console.WriteLine("p1: " + p1.X + ", " + p1.Y);
Console.WriteLine("p2: " + p2.X + ", " + p2.Y);
}
}
Now p1.X is 50 too.
This is why a struct is called a value type (the values are copied), and a class is called a reference type (the variables refer to the same object).
When to Use a Struct
Use a struct for small, simple data that belongs together, like a point (X and Y), a size (width and height) or a color (red, green and blue values).
Use a class for bigger things with more behavior, like a car or a player. If you are not sure, use a class.
| Struct | Class | |
|---|---|---|
| Keyword | struct | class |
| When you assign it to another variable | The values are copied | Both variables share the same object |
| Can inherit from another class | No | Yes |
| Best for | Small, simple data | Bigger things with more behavior |