Search⌘ K
AI Features

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.

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:

C# 14.0
namespace Structs;
struct Point
{
public double x;
public double y;
public void DisplayCoordinates()
{
Console.WriteLine($"The point's coordinates are ({x}, {y}).");
}
}
  • Line 1: Uses a file-scoped namespace to organize the code.

  • Line 3: Defines the Point type using the struct keyword.

  • Lines 5–6: Declares fields x and y to 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 ...