Struct
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
// Constructor to initialize the Point
public Point(int x, int y)
{
X = x;
Y = y;
}
// Method to display the point
public void Display()
{
Console.WriteLine($"Point({X}, {Y})");
}
}
public class Program
{
public static void Main()
{
// Create a new point
Point p1 = new Point(3, 4);
p1.Display(); // Output: Point(3, 4)
// Create another point using the default constructor
Point p2;
p2.X = 5;
p2.Y = 6;
p2.Display(); // Output: Point(5, 6)
}
}
Key Points
Memory Allocation: Structs are allocated on the stack (unless boxed). This makes them more efficient for small data structures.
Immutability: While structs can have mutable fields, they are often used as immutable types. Immutable structs ensure that their data cannot be changed after they are created.
Use Cases: Structs are best used for small, simple objects that have value semantics, such as coordinates, complex numbers, or RGB colors.