C# Structs
In C#, a struct is a value type data type that represents a collection of related data fields. In this tutorial, we'll discuss how to use C# structs and provide an example.
Syntax
The syntax for creating a struct in C# is as follows:
public struct MyStruct {
// fields
}
Example
Let's say we want to create a struct that represents a point in 3D space. Here's how we can define it:
public struct Point3D {
public int X;
public int Y;
public int Z;
public Point3D(int x, int y, int z) {
X = x;
Y = y;
Z = z;
}
}
Now, we can create objects of the Point3D struct and set their fields:
Point3D point1 = new Point3D(1, 2, 3);
Point3D point2 = new Point3D(4, 5, 6);
We can also access the fields of the Point3D objects:
Console.WriteLine(point1.X); // Output: 1
Console.WriteLine(point2.Y); // Output: 5
Output
When we run the example code above, the output will be:
1
5
This is because we created two Point3D objects and set their fields, then printed the values of some of those fields to the console.
Explanation
In the example above, we created a struct called Point3D that represents a point in 3D space. The struct has three fields that represent the X, Y, and Z coordinates of the point.
We then created two Point3D objects and initialized their fields using the constructor of the struct. Finally, we printed the values of some of the fields of the Point3D objects to the console.
Use
Structs are useful when you want to group related data fields together in a single data type. They are often used to represent simple data types like integers, floats, and doubles.
Important Points
- Structs are value types, which means they are stored on the stack instead of the heap.
- Structs can't inherit from other structs or classes, but they can implement interfaces.
- Structs must have a parameterless constructor defined if you want to instantiate them without passing any arguments.
Summary
In this tutorial, we discussed how to use C# structs and provided an example. We covered the syntax, example, output, explanation, use, important points, and summary of C# structs. With this knowledge, you can now use structs in your C# code to group related data fields together in a single data type.