Structures
In C#, a structure, or struct for short, is a value type that can encapsulate a set of related data fields. Like classes, structs can have properties, methods, constructors, and operators, but they have some important differences.
One major difference between structs and classes is that structs are value types, which means that when you assign a struct variable to another variable, the entire struct is copied. This is in contrast to reference types like classes, where only a reference to the object is copied.
Here's an example of how to define a struct in C#:
struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
public void Move(int dx, int dy)
{
X += dx;
Y += dy;
}
}
In this example, we define a struct named Point that has two public fields, X and Y, a constructor that initializes the fields, and a method named Move that changes the values of the fields.
You can create instances of a struct by using the new operator:
Point p = new Point(0, 0);
In this example, we create a new instance of the Point
struct and assign it to a variable named p
.
You can access the fields and methods of a struct using the dot notation:
p.X = 10;
p.Y = 20;
p.Move(5, 5);
In this example, we change the values of the X and Y fields and call the Move method to move the point by 5 units in both directions.
Structs are useful for encapsulating small sets of related data fields and can be more efficient than classes for certain types of operations. However, they cannot be inherited or used as a base class, and they are typically not used for large or complex objects.
Comments
Post a Comment