Defining and Using a Struct

In C#, a struct is a user-defined value type.  It’s typically used to contain a set of related value types, but can also contain reference types.  Because structs are value types, they stored their values directly rather than being allocated on the heap.  Struct parameters passed to a method are passed by value.
You define a struct as follows:
1
2
3
4
5
6
// A 3D point with a name
public struct Point3D
{
    public float X, Y, Z;
    public string Name;
}
Once you define a struct, you can define variables that belong to the new type and assign values to its fields.


1
2
3
4
5
6
7
8
9
10
11
Point3D first;
first.Name = "Herman";
first.X = 1.0f;
first.Y = 0.0f;
first.Z = 2.3f;
 
Point3D other;
other.Name = "Sally";
other.X = 2.0f;
other.Y = 0.0f;
other.Z = 4.6f;