Ch3shire Ch3shire - 3 months ago 24
C# Question

C# - ref this (reference to self)

Suppose I have a code in C++:

class A {
int x = 20;

void Interact(A* Other) {
if (x % 2 == 0) { Other->x++; x /= 2; } //some advanced operation
}
public:
void MakeInteraction(A* Other) {
Interact(Other);
Other->Interact(this);
}
};

int main() {
A a, b;
a.MakeInteraction(&b);
}


Problem is, if I want to make something similar in C#, I meet the barrier - of course I don't need to use pointers, but I can't use reference to
this
object:

class A
{
int x = 20;
void Interact(ref A Other)
{
if (x % 2 == 0) { Other.x++; x /= 2; }
}
public void MakeInteraction(ref A Other)
{
Interact(ref Other); //works
Other.Interact(ref this); //doesn't work
Other.Interact(this); //still doesn't work
A a = this;
Other.Interact(ref a);
this = a; //REALLY? THIS DOESN'T WORK TOO?!
}
}


I'm angry because I thought that C# corrects flaws of C++ and leaves as much options as originally C++, minus pointers. Now seems that switching from C++ to C# requires to change a way of thinking... again.

Answer Source

You don't need to use ref in your parameter declarations. For reference types like your class A, a parameter declared as just A other will cause C# to pass a reference to the object.

A parameter declared as A other in C# is similar to A* other in C++.

A parameter declared as ref A other in C# is similar to A** other in C++.

class A
{
    int x = 20;

    void Interact(A other)
    {
        if (x % 2 == 0) { other.x++; x /= 2; }
    }

    public void MakeInteraction(A other)
    {
        Interact(other);
        other.Interact(this);
    }

    static void Main()
    {
        A a = new A();
        A b = new A();
        a.MakeInteraction(b);
    }
}