Structs
Explore how to define and use structs in C#, including declaring fields, calling constructors, and initializing instances. Understand the key differences between structs and classes, such as memory handling and value versus reference types. This lesson prepares you to create efficient custom value types in your C# programs.
We'll cover the following...
Along with classes, structs let us create custom types in C#. Many primitive types, including int, double, and bool, are structs.
Let’s define a struct that represents a point in a two-dimensional space:
Line 1: Uses a file-scoped namespace to organize the code.
Line 3: Defines the
Pointtype using thestructkeyword.Lines 5–6: Declares fields
xandyto store the location.Lines 8–11: Defines a method to print the coordinates to the console.
Like classes, structs can store state in fields and define behavior via methods. In our case, we create x and y fields to store the location of the point and the ...