Junior — Middle
Is it possible to implement a function inside a data structure, and how would it work?
sobes.tech AI
Answer from AI
In C#, a struct can contain methods, including functions. This allows encapsulating behavior along with data. Methods inside a struct work the same way as in classes, but it is important to remember that structs are value types, and passing a struct to a method creates a copy.
Example:
struct Point
{
public int X, Y;
public void Move(int dx, int dy)
{
X += dx;
Y += dy;
}
}
When calling Move on a struct instance, a copy is modified if the struct is not passed by reference. To make changes persistent, you can use ref or in parameters.