ref vs out in C#

Jak
Jak
Member
352 Points
151 Posts

It is very common interview question. I want to know, what is exact different between ref and out keyword in C#?

Thanks in advance...

Views: 8145
Total Answered: 1
Total Marked As Answer: 1
Posted On: 10-Jan-2016 04:07

Share:   fb twitter linkedin
Answers
indradaman sharma
indrada...
Participant
54 Points
17 Posts
Marked as answer      

Hi friends my answer is

Parameters are always passed by value to a method by default.If we want to pass them by reference then we can use either out or ref keyword.

Reference parameters basically never pass the value of a variable used in the method calling, instead they use the variable themselves. Rather than creating a new storage for that variable in the method declaration, the very same storage space is used, so the value of the variable in the member method and the value of the reference parameter will always be the same. Reference parameters require ref modifier as part of both the declaration and the calling.

Output parameters are very much like reference parameters. The variable specified at the time of calling doesn't need to have been assigned a value before it is passed to the called method. When the method is invoked completely we can read that variable as it is assigned by now.

Like reference parameters, output parameters don't create a new storage location, but use the storage location of the variable specified on the invocation. Output parameters need the out modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something as an output parameter.

In short language we can say that

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.

Posted On: 16-Jan-2016 12:44
banner

Blog

Active User (2)

 Log In to Chat