Ref vs Out
Out keyword
The out is a keyword in C# which is used for 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.
Another example can be:
You can't use the
in
,ref
, andout
keywords for the following kinds of methods:
Async methods, which you define by using the async modifier.
Iterator methods, which include a yield return or
yield break
statement.In addition, extension methods have the following restrictions:
The
out
keyword cannot be used on the first argument of an extension method.The
ref
keyword cannot be used on the first argument of an extension method when the argument is not a struct, or a generic type not constrained to be a struct.The
in
keyword cannot be used unless the first argument is a struct. Thein
keyword cannot be used on any generic type, even when constrained to be a struct.
Calling a method with an out
argument
out
argument 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.
Starting with C# 7.0, you can declare the out
variable in the argument list of the method call, rather than in a separate variable declaration. This produces more compact, readable code, and also prevents you from inadvertently assigning a value to the variable before the method call. The following example is like the previous example, except that it defines the number
variable in the call to the Int32.TryParse method.
Ref keywork
The ref is a keyword in C# which is used for passing the arguments by a reference. Or we can say that if any changes made in this argument in the method will reflect in that variable when the control return to the calling method. The ref parameter does not pass the property.
Difference between Ref and Out keywords
ref keyword
out keyword
It is necessary the parameters should initialize before it pass to ref.
It is not necessary to initialize parameters before it pass to out.
It is not necessary to initialize the value of a parameter before returning to the calling method.
It is necessary to initialize the value of a parameter before returning to the calling method.
The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter.
The declaring of parameter through out parameter is useful when a method return multiple values.
When ref keyword is used the data may pass in bi-directional.
When out keyword is used the data only passed in unidirectional.
Last updated