When a method is defined with an out parameter, why do I have to specify the out keyword when calling it. Its already there in the method definition, and the runtime should know that any parameter passed will be an out parameter.
It would make sense if the compiler will accept the argument with or without out keyword, with different semantic, but if you MUST add the keyword to make the code compile, whats the use? Shouldn't the compiler handle it automatically?
Same for ref
The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. The ref is a keyword in C# which is used for the passing the arguments by a reference.
The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition as well as in the calling method.
The out and the ref parameters are used to return values in the same variables, that you an argument of a method. These both parameters are very useful when your method needs to return more than one values.
In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument. The following example declares a variable named number before it is passed to the Int32. TryParse method, which attempts to convert a string to a number.
It is really great for readability. Also it will help you to avoid unexpected behaviors. While calling method with out param you will definitely know that the value of passed variable can be changed.
This requirement is not there for the compiler's sake. f (x, out y)
instantly informs whoever is reading the code that y
is going to be overwritten after f
returns, without the need of looking up the definition of f
, saving them mental CPU cycles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With