ByRef Parameters

Leaving out the “out” keyword, there’s four basic combinations available to us: some combination of a value or a reference type, passed ByVal or ByRef.

Passing a value type by value. (ValVal in the examples below.)

This one’s simple. You’re passing the actual value into the method. Any changes you make to the parameter variable inside the method are not visible in the caller.

Passing a value type by ref. (RefVal in the examples below.)

You’re passing a reference to the value. Any changes you make inside the method are visible in the caller.

Passing a reference type by value. (ValRef in the examples below.)

Here’s where it gets interesting. You’re passing a reference type. Any changes made to the members of the parameter variable are visible to the caller.

Passing a reference type by ref. (RefRef in the examples below.)

While I’m sure we could dream up a reason to do this, we’re not that cool. Just don’t. You’re passing a reference to a reference which 99.999% of the time provides no value.

Or as Microsoft says: DO NOT pass reference types by reference.

public class MyClass
{
    public int MyProperty { get; set; }
}

public class MyOtherClass
{
    public void ValVal(int myValue)
    {
        myValue = 6;
    }

    public void RefVal(ref int myValue)
    {
        myValue = 9;
    }

    public void ValRef(MyClass myObject)
    {
        myObject.MyProperty = 42;
    }

    public void RefRef(ref MyClass myObject)
    {
        myObject.MyProperty = 42;
    }
}

This is the simplified version. If anyone wants to have discussions about how technically the scope of a parameter variable is always just the method in which its defined because you’re actually passing pointers blah blah blah, let’s do lunch.

Or if you’re bored, go read Framework Design Guidelines. Good times.