Structure in C# Language
In the world of programming, understanding the fundamental building blocks of a language is crucial. In
In the world of programming, understanding the fundamental building blocks of a language is crucial. In
A structure in C# is a composite data type that groups together a set of variables of different data types. These variables, also known as fields, can represent related pieces of data. Structures are value types, which means that they store their actual data on the stack, rather than as references on the heap, like classes. This difference in memory storage has important implications for how they behave.
Let’s take a look at a simple example to illustrate the use of a structure. Suppose you want to represent a 2D point with X and Y coordinates:
public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
}
In this example, we define a structure Point with two fields, X and Y. We also provide a constructor to initialize the values of these fields.
Now, let’s create instances of the Point structure and see how they behave:
Point p1 = new Point(3, 4);
Point p2 = p1; // A copy of p1 is made
p2.X = 7;
Console.WriteLine($"p1: X = {p1.X}, Y = {p1.Y}");
Console.WriteLine($"p2: X = {p2.X}, Y = {p2.Y}");
The output will show that modifying p2 does not affect p1, as it’s a separate copy of the structure:
p1: X = 3, Y = 4
p2: X = 7, Y = 4
This demonstrates the difference between structures and classes, where modifying a copy of a structure doesn’t affect the original, unlike with class instances.
Subscribe to get the latest posts sent to your email.