How to define and use structures in C#
In C#, you can define a struct using the struct keyword. A struct is a value type that can contain data members and function members.
The following is an example demonstrating how to define and use struct in C programming.
using System;
struct Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public void Print()
{
Console.WriteLine($"Point: ({x}, {y})");
}
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point(10, 20);
Console.WriteLine($"p1.x = {p1.x}, p1.y = {p1.y}");
p1.Print();
Point p2;
p2.x = 30;
p2.y = 40;
Console.WriteLine($"p2.x = {p2.x}, p2.y = {p2.y}");
p2.Print();
}
}
In the example above, we first defined a structure named Point, which has two integer members x and y. Next, we defined a constructor Point(int x, int y) and a printing function Print() within the structure.
In the Main function, we created two variables of type Point, p1 and p2, and initialized their member variables. We can then directly access and modify the struct’s member variables, and call the struct’s member functions.
Be aware that structs are value types, so when they are assigned to another variable or passed as a parameter to a function, a copy of the value is made. Modifying a member variable of one variable will not affect another variable.
I hope this helps you!