C# – Passing “this” as an argument – C#

cxna

I'm currently playing about with some XNA stuff learning to program AI. Anyway, here's my situation: Class A has a function which takes a reference to an instance of class B, does some stuff to to it, and returns it. Class B contains an instance of Class A, and then calls the function from it.

Example in code:

Class A
{
    B classB;

    public A()
    {
        classB = new B();
    }

    public void Act()
    {
        this = B.Do(ref this);
    }
}

Class B
{
    public A Do(ref A classA)
    {
        //Manipulate
        return classA;
    }
}

I've tried passing a memberwise clone .. but that didn't work, obviously, because "this" is read-only. I've no idea with this. I'm really stuck. Does anybody have any ideas? I'd ideally like to avoid having to pass every single variable in the object as a separate argument, really.

Andy.

Best Answer

Classes are reference types, so doing

Class B
{
    public void Do(A classA)
    {
        //Manipulate
    }
}

should manipulate the object classA references. Then in A,

Class A
{
    B classB;

    public A()
    {
        classB = new B();
    }

    public void Act()
    {
        B.Do(this);
    }
}

Note: "This does have the side effect that the reference of A that you pass cannot be set to null (it will only set the local variable to null)" - JulianR