#107 – 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:

 // 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.

 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;
Advertisements