Structure in C# Language
In the world of programming, understanding the fundamental building blocks of a language is crucial. In C#,
one such building block is the structure. Structures provide a way to create complex data types, similar to classes, but they have some key differences that make them distinct. In this post, we’ll explore what structures are, how they differ from classes, and provide examples to illustrate their usage.What is a Structure in C# Language?
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.
Differences Between Structures and Classes
- Memory Allocation: As mentioned, structures are value types, and their data is allocated on the stack. Classes, on the other hand, are reference types, and their data resides on the heap. This makes structures more efficient in terms of memory usage.
- Copying Behavior: When you pass a structure to a method or assign it to another variable, a copy of the entire structure is created. With classes, you are working with references to the same data in memory.
- Default Constructor: Structures have a default parameterless constructor generated by the compiler, whereas classes require you to define constructors explicitly.
Example of a Structure
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.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.