I am trying to create a delegate to a struct method for a particular instance. However, it turns out that a new instance of the struct is created and when I call the delegate it performs the method over the newly created instance rather than the original.
static void Main(string[] args)
{
Point A = new Point() { x = 0 };
Action move = A.MoveRight;
move();
//A.x is still zero!
}
struct Point
{
public int x, y;
public void MoveRight()
{
x++;
}
}
Actually, what happens in this example is that a new instance of struct Point is created on the delegate creaton and the method when called through the delagate is performed on it.
If I use class instead of the struct the problem is solved, but I want to use a struct. I also know there is a solution with creating an open delegate and passing the struct as the first parameter to a delegate, but this solution seems rather too heavy. Is there any simple solution to this problem?