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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #107 – Defining and Using a Struct

  1. Pingback: #327 – Assigning a struct to a New Variable Makes a Copy « 2,000 Things You Should Know About C#

  2. Pingback: #519 – Differences Between structs and classes « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: