Defining Struct and Record Struct Types

Learn about defining custom value types using the struct keyword and enhancing them with the record keyword.

We’ll delve into the realm of defining struct types in C#. These value types offer benefits like memory efficiency and improved performance. So, let’s begin our journey into the struct types and discover how they can enhance our C# programming skills.

Defining struct types

Let’s explore defining our value types:

Step 1: In the PacktLibrary project, add a file named DisplacementVector.cs.

Step 2: Modify the file, as shown in the following code, and note the following:

  • The type is declared using a struct instead of a class.

  • It has two int properties, named X and Y, which will auto-generate two private fields with the same data type that will be allocated on the stack.

  • It has a constructor for setting initial values for X and Y.

  • It has an operator for adding two instances together that returns a new instance of the type with X added to X and Y added to Y:

Get hands-on with 1400+ tech skills courses.