Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between the 'ref' and 'out' keywords?

I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:

public void myFunction(ref MyClass someClass) 

and

public void myFunction(out MyClass someClass) 

Which should I use and why?

like image 675
TK. Avatar asked Dec 23 '08 09:12

TK.


People also ask

What is the difference between the ref and out keywords Linkedin?

The ref and out keywords both use the concept of Pass by Reference with data, but with some compiler restrictions. You can think ref keyword as two way where data passed from caller to callee and back while out keyword is a one way, it sends data from calle to caller and any data passed by a caller is discarded.

What is the difference between the ref and out keywords Mcq?

Explanation: Variable 'i' is passed as reference parameter declared with 'ref' modifier and variable 'j' is passed as a output parameter declared with 'out' keyword. Reference parameter used to pass value by reference is the same with out parameter.

What does the out keyword do?

You can use the out keyword in two contexts: As a parameter modifier, which lets you pass an argument to a method by reference rather than by value. In generic type parameter declarations for interfaces and delegates, which specifies that a type parameter is covariant.

What are Ref keywords?

The ref keyword indicates that a value is passed by reference. It is used in four different contexts: In a method signature and in a method call, to pass an argument to a method by reference. For more information, see Passing an argument by reference. In a method signature, to return a value to the caller by reference.


1 Answers

ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

So while ref is two-ways, out is out-only.

like image 188
Rune Grimstad Avatar answered Sep 22 '22 03:09

Rune Grimstad