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.
Output for the above code
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.
Output shows
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
Output as follows
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.
Great !
I recently got to know that we cannot use ref & out keywords in async methods