Monday, June 13, 2005

What's the difference between the 'out' and the 'ref' parameters in .NET?

A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns.

An argument passed to a ref parameter must first be initialized. Compare this to an 'out ' parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.

Now the big question is why did Microsoft go thru the pain of having both 'ref' and 'out' ?

The answer is in the snippet below:

The two parameter passing modes addressed by out and ref are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors.

These include:
not assigning a value to an out parameter in all control flow paths
not assigning a value to variable which is used as a ref parameter

Because the C# language assigns different definite assignment rules to these different parameter passing modes, these common coding errors are caught by the compiler as being incorrect C# code.
The crux of the decision to include both ref and out parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having both ref and out parameter passing modes in the language.