Alex Rivera | Logout

Can I pass primitive types by reference in C#?

Asked 2011-08-19T13:17:04.930
15

I know complex types are passed by Reference in C# and primitive types are passed by Value. Can I pass primitive types by reference in C#?

Update:

Thanks for answers, but my example is?

void test(object x) {

}

long y = 1;

test(ref y);

This throw this exception: The 'ref' argument type doesn´t match parameter type

Edit
Report

1 Answer

1

Post-update you can pass boxed values around by reference.

static void Main(string[] args)
{
    var value = 10;
    var boxed = (object)value;
    TakesValueByRef(ref boxed);
    value = (int)boxed;
    // value now contains 5.
}

static void TakesValueByRef(ref object value)
{
    value = 5;
}

Just keep in mind it's terrible practice, and risky (due to cast exceptions) to do this.

answered 2011-08-19T13:49:30.917

Your Answer