Ref and Out Parameter in C#


Introduction

Hi all . before starting this article i wanted to say that this article is all about "Ref and Out" and this is one of the fundamental part of c# ,which play most important role in our day to day programming.


Get Started

Basically both the keywords used to return the value as a reference type. But both have different purpose in c# programming. 

Lets started ...........


Description

RefNeed to be Initialized before calling the function. 
OutValue is initialized in the called function .

If the above point is not understandable now then , Lets see the above point in action.



























See the above code .
For "Ref" we initialize variable first(val1) , then pass the value to the function and return back the result.
So Ref is used to serve two way communication.

For "Out" we just declare variable(val2) and return back the result.
So the Out is used for one way communication.

You can see the output below.







So we can see the expected output above.

There is a question comes to our mind that if we are not initializing the variable in case of "Ref" then what will happen. 
See the below in action.



You can see a compiler error saying that val1 is unassigned.


Conclusion

Ref and Out used to return the value . When we have a requirement to return a value from a method of type "void" then we can use these keyword.


Thanks........



Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts