Saturday, July 07, 2007

What is “ref” keyword in C#

What is “ref” keyword in C#

“ref Keyword” in C#.

Passing variables by value is the default. However, we can force the value parameter to be passed by reference.

Point to be kept in mind while using ref keyword.
variable “must” be initialized before it is passed into a method.


Example, Without Using ref keyword
class Test
{
public static void Main()
{
int a = 3;
DoWork(a);
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(int i)
{
i++;
}
}
The program will result in : The value of a is 3


Example, With the Use of ref keyword
class Test
{
public static void Main()
{
int a = 3; // must be initialized
DoWork(ref a); // note ref
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(ref int i) // note ref
{
i++;
}
}
The program will result : The value of a is 4

No comments:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape