Published: 23 Mar 2012
By: Akhil Mittal

Knowing the power of ref and out, a developer will certainly make full use of this feature of parameter passing. My effort in this article would be to make this understanding simpler and focus on internal logic of ref and out.

Contents [hide]

Introduction

One might incorporate n number of methods to return or pass parameters while method calling. Most of the time a developer ties to escape using c# feature of parameter passing by reference. Had he know the power of ref and out, a developer will certainly make full use of this feature of parameter passing. My effort in this article would be to make this understanding simpler and focus on internal logic of ref and out.

Value Types vs Reference Types (Quick Overview)

As we know that in C# .NET there are two types of "types": reference types and value types. Since they act in their own special way, they must always be used according to the real need and not by force.

Reference type variables have their value a reference to the appropriate data rather than the data itself.Its ByRef in VB6, & in c++.

Value types directly contain the data and not the reference. And when assigned the copy of that data is made to the assignment. To elaborate, a new storage space is created for the variable in the function member declaration, and it starts off with the value that we specify in the member method calling. If we change that value, it doesn't affect any variable involved in that call.

Why Pass by Reference?

While writing a code, we often come across situations where in we need to return multiple values from a single function/method. But a method can only return a single value.The question is how do we overcome such situation.Answer is simple, use reference types, but how?

Let's throw some light on when to use the methodology. When you pass in a variable to a method, the value of that variable gets copied to the method by default. For values types, it means that the object itself gets copied on the other end for reference types. It means that only the thing that points at the object gets copied.

It is one way to save performance, else as larger as the reference type would be as more performance it would cost. So we can also refer this as "Call by Sharing". In a call by reference situation, if the variable of a reference type is changed inside the method, the caller variable also gets affected. If we change the value of a value type, when passed to a method, it will never affect the caller variable.

Our Target (Ref and Out)

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.

Consider the following scenario. I have developed a simple console application to clarify the logic with the following code in Program.cs file.

As we can see in the above easy to understand code, I have created two methods RefMethod and OutMethod to handle passed parameter into their invocation. Just to check what were the values of my variables before and after assignment ,When I compiled the code I got the following compile time error.

Certainly the error helped me to discover some new facts about out and ref:

  • The parameter initially is considered not assigned in case of out.
  • The variable specified at the time of calling doesn't need to have been assigned a value before it is passed to the function member. It's the responsibility of called method to assign it before completing the execution so that we can read it.

I changed the code to the following:

And as expected, it worked fine. Then to check if same is the case with ref also, I again made some modifications as follows:

This time I got the following compile time error:

That means that unlike out, when using ref:

  • Parameter must be initialized before calling the function.

Therefore out and ref basically add something new to the meaning of "pass by reference" by specifying that the variable must be initialized and will be modified (ref) and that the same will be initialized inside of the function (out).

The Inside Story (Some points to remember)

  • Several inbuilt methods as TryParse (one of my favorite) use out and not ref as the inside the internal implementation the library mainly uses ref. Therefore out is a special form of ref in which the referenced memory should not be initialized before the call.
  • Both the method definition and the calling method must explicitly use the ref / out keyword.
  • There is no "boxing" when a value type is passed by reference.
  • Properties cannot be passed via out or ref, as properties are actually methods.
  • ref/out are not considered to be a part of method signature at compile time, so methods cannot be overloaded, if the only difference between them is that one of the methods takes a ref argument and the other takes an out argument.

Here is the final (running) code:

And here's the output:

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Akhil Mittal

I currently work as an Engineer Analyst in anMNC and have an experience of about 5 years in C#.Net. I am a B.Tech in Computer Science and hold a diploma in Information Security and Application Development. My work experience includes Development of Enterprise Applications using C#,.Net and Sql Serve...

This author has published 4 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Android for .NET Developers - Location and Maps
In Windows Phone and iOS getting the current position of the device in terms of latitude and longitu...
Developing a Hello World Java Application and Deploying it in Windows Azure - Part I
This article demonstrates how to install Windows Azure Plugin for Eclipse, create a Hello World appl...
Android for .NET Developers - Using Web Views
In this article, I'll show a native app that contains a web-based view. The great news is that HTML ...
Android for .NET Developers - Building a Twitter Client
In this article, I'll discuss the features and capabilities required by an Android application to ta...
Developing a Hello World Java Application and Deploying it in Windows Azure - Part II
In this article we will see the steps involved in deploying the WAR created in the first part of thi...

You might also be interested in the following related blog posts


Visual Studio 2010 Extension Manager read more
Naming Anonymous Types with Generate from Usage read more
RadControls for ASP.NET AJAX - Now with more speed! read more
Private Extension Methods read more
Victory In Software Development read more
Sneak Peek: ASP.NET Splitter Control read more
Telerik Releases New Controls for Silverlight 3 and WPF read more
Dovetail is Hiring a Junior-to-Mid-level .NET Developer read more
API changes introduced by the new CoverFlow control read more
Multi-Targeting Support (VS 2010 and .NET 4 Series) read more
Top
 
 
 

Discussion


Subject Author Date
placeholder Nice Article. Ekta Garg 3/23/2012 12:16 PM
Great Article Ambika Nagpal 3/26/2012 4:03 AM
placeholder Good explaination Vivek Johari 3/26/2012 6:44 AM
Very easy to understand !! Udeep Kansal 3/31/2012 9:24 AM

Please login to rate or to leave a comment.