Monday, September 26, 2011

out and ref Parameters in C#

Today I am going to write about two nice modifiers that we can use when defining parameters in a method. While parameters are very simple and straight forward to use, there are tricks which can make them a lot more powerful than it seems.

C#, as well as other languages have two types of parameters. One is passing parameters 'by value' and the other is 'by reference'. The default is 'by value'. If we pass a parameter 'by value', that means we are passing a variable to a method and actually we are sending a copy of a variable instead of a reference to it. What happens here is, all the changes we do to that variable in our method, will not affect the original variable which we passed as a parameter.

If you want to pass parameters 'by reference', that's where out and ref modifiers comes in. With the help of out and the ref keyword, we can change this behavior, so we pass along a reference to the object instead of its value.

Difference between out and ref

Actually these two modifiers pretty much acts like the same. They both ensure that the parameter is passed 'by reference' instead of 'by value', but they have one significant difference. That is when we are using out parameter, before passing the variable into the method we don't have to initialize the variable. But in the method before leaving the method, we should assign a value for that. If not we will get a compile error saying "The out parameter 'x' must be assigned to before control leaves the current method".

When we are using ref parameter, before we pass the variable into the method, we must initialize it. if not we will get a compile error saying "Use of unassigned local variable".

I am going to write down a simple code, so you will be able to get a good understanding about how to use these two modifiers and their difference.

using out modifier

static void Main(string[] args)
{
     int i; //no need to assign a value to i
     Method(out i);
     Console.WriteLine(i); //i is 10
     Console.ReadLine();
}

static void Method(out int x)
{
     x = 10; //must assign a value
}

using ref modifier

static void Main(string[] args)
{
     int i = 5; //must initialize the variable
     Method(ref i);
     Console.WriteLine(i); //i is 10
     Console.ReadLine();
}

static void Method(ref int x)
{
     x = 10; //can change the value, but not a must
}

As you can see, when I am using out modifier I did not set a value to the variable before passing it. But in the method I have set a value and it is a must. When using ref modifier, I have initialized the variable and then passed it. Without initializing the variable I can't use ref and in the method, it's up to you to change the value or not. Hope you all got a good understanding in out and ref.

Feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment