Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ref vs out in C# [duplicate]

Tags:

c#

.net

types

Possible Duplicate:
Difference between ref and out parameters in .NET

When to use ref and when to use out ? What is difference between the both ? How and where they are used ?

Please share an example showing difference between the both ref and out .

  • Thanks.
like image 390
Pratik Avatar asked Nov 15 '10 17:11

Pratik


People also ask

What is difference between ref and out?

ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.

What is ref in C?

When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.

What is the difference between ref and out keywords with example?

Here is a list of the differences between Ref and Out Keywords in C#. We use the ref keyword when a called parameter needs to update the parameter (passed). We use the out keyword when a called method needs to update multiple parameters (passed). We use this keyword for passing data in a bi-directional manner.

Why do we use ref and out in C#?

ref keyword is used when a called method has to update the passed parameter. out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way. out keyword is used to get data in uni-directional way.


1 Answers

To my understanding:

ref means passing a variable by reference, which means you pass a pointer to that variable and it will retain modifications after leaving the function.

out means basically the same, except that the variable must be assigned before the function is exited, pretty much like return statements must be met before the function reaches completion.

like image 138
bevacqua Avatar answered Oct 03 '22 15:10

bevacqua