C# Out Parameter Explored

Poonamkalra
Posted by in C# category on for Intermediate level | Points: 250 | Views : 5577 red flag

While going through the msdn link http://msdn.microsoft.com/en-us/library/t3c3bfhx%28v=vs.71%29.aspx that contains documentation about "out" method parameter, I got stuck with the line "The value of an out argument will not be passed to the out parameter".

Introduction

To understand this behaviour I have written a small piece of code containing a caller function with an out argument and a callee function with an out parameter.


The above code contains two functions “TestOutputArgument” and “TestOutputParameter”. But this code has a compilation error!  In function "TestOutputParameter" value of out parameter "a" is used without assignment. Please note that this is despite of the fact that "a" has been assigned some value in the caller function “TestOutputArgument”. 

In the above rectified code, value of "a" in “TestOutputArgument” function before calling function “TestOutputParameter” is 75. Upon stepping through "TestOutputParameter" in debug mode, value of "a" is still shown as 75 in the debug window. But the complier won’t let you access its value and will throw a compilation error if the out parameter is accessed without assigning any value.


This complies with the Microsoft’s definition for out parameter that "A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns."

Below is the output of the above code

Hope this will help clarifying the out parameter in C#. 

Thanks for reading

Page copy protected against web site content infringement by Copyscape

About the Author

Poonamkalra
Full Name: Poonam Kalra
Member Level: Starter
Member Status: Member
Member Since: 8/30/2010 6:35:33 AM
Country: India

http://poonamkalra.blogspot.com/
8.0 years of experience in software industry including 5.0 years of experience in .NET framework

Login to vote for this post.

Comments or Responses

Posted by: Jpchoudhari on: 8/17/2011 | Points: 25
yes, the first scenario is correct; one has to assigned value to out parameter in called function before control leaves or before using the variable itself in the called method.

Login to post response

Comment using Facebook(Author doesn't get notification)