C# Imp. Basics - Ref and Out parameters
Well, I am still learning .net, so please excuse me for some confusing words.
Sometimes there is a confusion whether to pass the parameters to a method byreference (ref keyword) or using out keyword. As, both keywords are sometimes confused to be used to get the multiple return values from the target method.
1. When to use ref:
the parameters that are needed to be changed by the target method and the change in value is required to be visible after the method call returns should be passed byref.
first, the key thing to remember is that each parameter passed by ref must be initialized before passing to the target method (which will finally change their values) and the change will be visible after the target method call returns.
secondly, it is not mandatory to change the values of any of the parameter recieved as by ref in the target method.
---------------------------------------------------------------------------
2. When to use out:
out parameters are used when there is a certain need to return multiple values from a method call.
first, its not mandatory to initialize each parameter marked as out in the target method, before calling that method.
secondly, each parameter which is marked as out in the target method, must be assigned a value corresponding to its type in all code return paths of the target method implementation (otherwise compile error).
---------------------------------------------------------------------------
Hope the readers understand what i have tried to explain. Suggestions and questions are always welcome.
Note: out parameters are not supported in the Visual Basic.Net language
Reference: Essential C# 2.0 by Mark Michaelis
Comments