passing parameters in C#
What i knew about 'out' parameter in c# is that if we
want to return more than one from a single routine. But we can use
'ref' to return more than one from a single routine.Ofcourse ' out '
parameter also passed as reference variable.
Then what is the need of 'OUT' ? where exactly we need 'out'? Please
explain with real time situation.
VulpesPosted May 15, 2013, 8:09 AM
However, you'd generally prefer 'out' to 'ref' if you don't want to have to assign a value to the 'out' parameter first (with 'ref' you have to assign a value).
With an 'out' parameter, the compiler guarantees that it will have been assigned a value (in all possible paths) before the method returns.
There is no such guarantee with a 'ref' parameter which may come back from the method with the same value that it had to start with.
A good example of an 'out' parameter in practice is the Int32.TryParse (string, out int) method.
This returns a bool value indicating whether the string was successfully parsed to an Int32 or not. A value is also returned in the 'out' parameter representing the result of a successful parse or 0 otherwise. So:
int i, j;
bool isValid = int.TryParse("abc", out i);
// isValid is false and i is 0
bool isValid2 = int.TryParse("123", out j);