Structs

Structs are another way to define custom types in .NET.

Creating structs

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:

struct Point
{
	public double x; 
	public double y;

	public void DisplayCoordinates()
	{
		Console.WriteLine($"The point's coordinates are ({x}, {y}).");
	}
}

Like classes, structs can store the 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 DisplayCoordinates method that prints these fields to the console.

Use structs

Let’s use the struct we created in a program.

Get hands-on with 1200+ tech skills courses.