C# Struct

In C#, a struct is a value type that is used to encapsulate small groups of related variables. It is similar to a class in terms of syntax but has some differences in usage and behavior. In this article, we will explore the concept of struct in C# with examples.

Defining a Struct

To define a struct in C#, we use the struct keyword followed by the name of the struct. Here's an example of a simple struct:

1struct Point 2{ 3 public int X; 4 public int Y; 5}

In the above example, we have defined a struct named Point that has two public fields of type int named X and Y.

Note that by default, all fields in a struct are private. We have explicitly made them public in this example to make them accessible outside the struct.

Creating a Struct

To create a new instance of a struct, we use the new keyword followed by the name of the struct. Here's an example:

1Point p = new Point(); 2p.X = 10; 3p.Y = 20;

In the above example, we have created a new instance of the Point struct using the new keyword and set the values of its fields.

Struct vs Class

One of the main differences between a struct and a class in C# is that a struct is a value type, while a class is a reference type. This means that when you create a struct, it is stored on the stack, while a class is stored on the heap.

Another difference is that a struct cannot inherit from another struct or class, and it cannot be inherited from. It also does not support inheritance, polymorphism, or virtual methods.

Example: Point Struct

Let's take a look at a more complete example of using a struct in C#:

1using System; 2 3struct Point 4{ 5 public int X; 6 public int Y; 7 8 public Point(int x, int y) 9 { 10 X = x; 11 Y = y; 12 } 13 14 public void Print() 15 { 16 Console.WriteLine($"({X}, {Y})"); 17 } 18} 19 20class Program 21{ 22 static void Main(string[] args) 23 { 24 Point p1 = new Point(10, 20); 25 p1.Print(); 26 27 Point p2 = new Point(30, 40); 28 p2.Print(); 29 } 30}

In the above example, we have defined a struct named Point that has two public fields of type int named X and Y. We have also defined a constructor that takes two int arguments and sets the values of X and Y.

We have also defined a method named Print that prints the values of X and Y to the console.

In the Main method, we create two instances of the Point struct using the constructor and call the Print method on each instance.