Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# delegate to struct method

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?

like image 573
Oggy Avatar asked Feb 23 '11 02:02

Oggy


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


1 Answers

No, there's no way around this. Do you have a specific reason to use struct? Unless you have a particular need for it, you really should be using class.

Incidentally, you have created a mutable struct (a struct whose values can change), which is, without exaggeration, anathema. You need to be using a class.

like image 184
Adam Robinson Avatar answered Sep 24 '22 15:09

Adam Robinson