C sharp Difference between the out and ref type parameters

Hi,

In C Sharp(C#) we can have three types of parameters in a function. The parameters can be In parameter (which is not returned back to the caller of the function), Out parameter and ref parameter (where by a reference to the variable is passed back).

The last two type (out and ref) mentioned looks quite similar in nature. Both parameters are used to return back some value to the caller of the function. But still there is a small but important difference between them. Both of the parameter type has been kept in the C# language for specific scenario.

The main difference between the two types is in the rule for definite assignment of them.

When we use the out parameter, The program calling the function need not assign a value to the out parameter before making the call to the function. The value of the out parameter has to be set by the function before returning the value.

The same is not true for the reference (ref) type parameter. For a ref type parameter, the value to the parameter has to be assigned before calling the function. If we do not assign the value before calling the function we will get a compiler error.

Another important thing to note here is that in case of ref parameter, the value passed by the caller function can be very well used by the called function. The called function does not have the compulsion to assign the value to a ref type parameter. But in case of the out parameter, the called function has to assign a value.

Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 10/23/2007 7:59:29 AM

Please explain with examples of each, that would be better to understand

Posted on 10/24/2007 9:34:29 PM

good but make very good if explain with example.

thanks

Posted on 10/29/2007 4:10:08 AM

Good explanation...

Posted on 11/4/2007 11:33:11 PM

Yes I agree with Sanjay. The Topic is very good but would have been more better with some simple examples. Thanks

Posted on 11/4/2007 11:34:10 PM

Very good Topic but would have been more better with some simple examples. Thanks

Posted on 11/11/2007 1:32:04 AM

Nice article Vikram, as always!!Very specific, Just one thing I would request you, could you explain this a bit elaborately, I mean with examples?

Posted on 12/28/2007 11:13:34 AM

Very nice. I can understand with out even examples

Posted on 7/9/2008 12:27:03 AM

example is needed for better explanation, thanks

Posted on 9/18/2008 6:06:47 AM

Very well explanation. It clear the concept of ref param and out param.

Posted on 9/24/2008 5:25:18 AM

Its very helpful.Thanks

Posted on 9/24/2008 5:26:51 AM

Its very helpful.Thanks

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia