Im reading some C# documentation about WCF and IDispatchMessageInspector and the interface defines a 'Message' object that is passed by reference so that it can be manipulated.
What actually happens on the stack when you pass something by ref as opposed to passing normally?
It's not the object that's passed by reference - it's the variable.
Basically it aliases the variable used as the argument from the calling side, and the parameter in the method that you call:
public void Foo()
{
int x = 10;
Bar(ref x);
Console.WriteLine(x); // Prints 20
}
public void Bar(ref int y)
{
y = 20;
}
Here, x and y are essentially the same variable - they refer to the same storage location. Changes made to x are visible via y and vice versa. (Note that in this case it's a local variable in the caller, but it doesn't have to be - if you'd passed an instance variable by reference, then Bar might call another method which changes the same variable, and then y would be seen to "magically" change...)
For more about parameter passing in C#, refer to my article on the subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With