A struct (struct) in C# is a value type that encapsulates data and related methods. It is similar to a class, but it is stored on the stack instead of the heap, making it more efficient for small data structures.
using System;
struct Point
{
public int X; // Field for X coordinate
public int Y; // Field for Y coordinate
}
class Program
{
static void Main(string[] args)
{
Point p = new Point { X = 5, Y = 10 }; // Creating and initializing a struct
Console.WriteLine($"Point: ({p.X}, {p.Y})");
}
}
// output:
Point: (5, 10)
A struct in C# can have fields, properties, and methods, just like a class. However, since it is a value type, it is stored on the stack, making it more efficient for small, simple objects.
using System;
struct Rectangle
{
public int Width; // Field for width
public int Height; // Field for height
// Method to calculate area
public int GetArea() => Width * Height;
}
class Program
{
static void Main(string[] args)
{
var rect = new Rectangle { Width = 5, Height = 4 }; // Create and initialize a struct
Console.WriteLine($"Area: {rect.GetArea()}"); // Output: Area: 20
}
}
// output:
Area: 20
A struct array is an array that holds multiple instances of a struct. Since structs are value types, each element in the array stores a copy of the struct.
using System;
struct Point
{
public int X; // Field for X coordinate
public int Y; // Field for Y coordinate
}
class Program
{
static void Main(string[] args)
{
// Creating an array of structs
Point[] points = new Point[2];
// Initializing struct instances
points[0] = new Point { X = 1, Y = 2 };
points[1] = new Point { X = 3, Y = 4 };
// Iterating through the array
foreach (var point in points)
{
Console.WriteLine($"Point: ({point.X}, {point.Y})");
}
}
}
// output:
Point: (1, 2)
Point: (3, 4)