Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the equivalent to passing by address in c#

Tags:

c++

c

c#

void Afunction(int* outvar)
{
    if(outvar)
        *outvar = 1337;
}

note the qualities: it allows you to optionally pass a variable by reference, so that it can be set by the function.

my closest guess would be (ref int? outvar)

but that produces ref (int?) NOT (ref int)? which is what I need

this functionality is hardly a scarcely used feature of c or c++, so I assume there must be some equivalent? Edit: so let me try a good example, I think a Colision check function is a prime example, where you have the primary test being whether or not two objects are in contact, then the optional output of the projection vector, calculating the projection vector takes extra time, so you only want to do it if they want it, on the other hand, it usually uses alot of the info calculated when doing the collision test.

bool Collide(colObject obj1, colObject obj2, Vector3* projection)
{

    //do a bunch of expensive operations to determine if there is collision
    if(!collided)return false;
    if(projection != NULL)
    {
        //do more expensive operations, that make use of the above operations already done,
        //to determine the proj vect
        *proj = result;
    }
    return true;
}

note that I am currently just porting c++ code to c#, so I might not have though of any real 'out of the box' solutions

like image 308
matt Avatar asked Dec 07 '22 02:12

matt


1 Answers

The best you can get in C# is Action<int>, like this:

void MyFunction(Action<int> valueReceiver) {
    if (valueReceiver != null)
        valueReceiver(1337);
}

Usage:

MyFunction(null);
MyFunction(v => someVariable = v);
like image 53
SLaks Avatar answered Dec 09 '22 14:12

SLaks