Come on let’s talk .. ..

I was reading a book last night and noticed plenty of codes in that book were using ‘ref’ in the methods. Mmm.. plenty in the sense almost all of them except where the example methods have some value type parameters.

Here’s a simple example, (a screen shot of the page)

image

Then I thought we all know that reference types are passed to methods as reference (though the pointer is passed as a copy), there is no any specific need to have the ‘ref’ keyword. (Please correct me if I’m wrong)

Unless you can save few bytes of memory for the new pointer in the stack. 🙂 which will be kicked out immediately after the code/methods returns.

I have already made a post on ‘ref’ and ‘out’ keywords. (See here) These two keywords are really very interesting bits of C#.

ref & out in C#

This post explains about the ‘ref’ and ‘out’ keywords in C#. In C# we have two types; 1) value types 2) reference types.

Value types variables are passed as copies to the methods and any changes inside a method does not affect the variable. ‘ref’ keyword is used to pass a value type as a reference type.

 

Have look on this code sample and the output.

image

 

Output for the above code

image

 

This is because the value is passed as a copy.

Let’s see hoe to use the ‘ref’ keyword to pass the value types as references in C#.

In order to do this you have to make the change in the methods declaration and as well when you call the method also you have to mention the ‘ref’ keyword.

 

Sample show what exactly you have to do.

image

Output shows

image

 

Now let’s have a look on where to use the ‘out’ keyword. The main purpose of the ‘out’ keyword is that it enables us to create and use uninitialized variables for output. Some ways it can be used to return more than one value.

But ‘out’ keyword is powerful since it uses the local variables to be used in such purposes rather than the traditional use of global variables.

We can accomplish the above task by other ways as well, but still ‘out’ keyword is handy. We can see that the ‘out’ keyword is used in some of the .NET framework methods.

Sample of ‘out’ keyword usage

image

 

Output as follows

image

 

Look that x is local variable and it is initialized in another method. This very handy and powerful concept.

As we can see both of these key words we can assure that ‘ref’ and ‘out’ pass the pointers to the methods with some framework built in restrictions.

And another nice feature of the C# compiler is that it checks whether any methods that initialize the x has been called before accessing it.

If you comment the line myMethod(out x);  and compile the code, it will complain that you are trying to use an unassigned variable.

So it is very safe and nice yet powerful as well.