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;
        }


1 comment:

Gabe Co Hadwin said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.