Out vs Ref in C#
In C#, the out keyword is used to pass an argument to a method by reference. This means that the method can modify the value of the…
In C#, the out
keyword is used to pass an argument to a method by reference. This means that the method can modify the value of the argument, and those changes will be reflected in the calling code. Here's an example:
In the example above, the Divide
method takes three arguments: numerator
, denominator
, and result
. The result
argument is marked with the out
keyword, which means that the Divide
method can modify its value. When the method is called, the result
variable is passed by reference, so when the method divides numerator
by denominator
and assigns the result to result
, the result
variable in the main
method is updated with the new value.
On the other hand, the ref
keyword is also used to pass an argument to a method by reference. The main difference between out
and ref
is that ref
requires that the argument be initialized before it is passed to the method, whereas out
does not. Here's an example of the ref
keyword in action:
In the example above, the Divide
method is the same as the previous example, but this time the result
argument is marked with the ref
keyword. This means that the result
variable must be initialized before it is passed to the Divide
method. In the main
method, the result
variable is initialized to 0
before it is passed to the Divide
method. Then, when the Divide
method is called, it updates the value of result
with the result of the division, and this new value is reflected in the main
method.
So to summarize, the main difference between out
and ref
is that out
parameters do not need to be initialized before they are passed to a method, whereas ref
parameters do.
If you like my work you can help me in growing through following ways