Thursday 3 September 2009

C# - Difference between 'out' and 'ref'


When passing objects as parameters to functions, there may be a certain scenario where you wish to modify a parameter before a function call, modify its valur within the function, and retain its value after the function call... This example behaviour describes the actions of the 'ref' qualifier to a function argument. 'out' however, is quite similar...

ref qualifier
When passing an object to function, specifying it as ref requires the object to be initialised beforehand. You can then modify its value inside the function and continute to use the object once the function call has ended.

Example
        private void ModifyByFive(ref int number)
        {
            number += 5;
        }


out qualifier
When passing an object to function, specifying it as out does not require the object to be initialised beforehand. However, the object can then be modified for this purpose within the function, and can be used outside the function once the function has executed. This can be treated as an 'extra return value'. However, using too many out parameters might require an architectural re-think; as a class or struct might prove more benificial.

Example
        private void ModifyByFive(out int number)
        {
            number += 5;
        }


No comments: