CSharp ref keyword used to pass parameters by reference not by value. This means any change to parameter inside method will reflect to calling method variable. In pass by value if you change objects members then they will reflected in calling method variable but if you assign new object then calling method variable has no effect.
Table of content
Points to remember
- An argument that is passed to a
refparameter must be initialized before it is passed. - Overloading can be done when one method has a
reforoutparameter and the other has avalueparameter. - Can not overload method with one
refotherout. It will give Compiler error CS0663: Cannot define overloaded methods that differ only on ref and out. - Property, indexers, dynamic types can not be passed as
reforoutparameter. Asyncmethods, which you define by using theasyncmodifier can not usereforout.- Iterator methods, which include a yield return or yield break statement can not use
reforout.
Example
public class MyRefTest
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Foo();
Console.ReadLine();
}
public static void Foo()
{
MyRefTest myObject = new MyRefTest();
myObject.Name = "Dog";
Bar(myObject);
Console.WriteLine(myObject.Name); // Writes "Dog".
myObject.Name = "Dog";
Bar(ref myObject);
Console.WriteLine(myObject.Name); // Writes "cat".
}
public static void Bar(MyRefTest someObject)
{
MyRefTest myTempObject = new MyRefTest();
myTempObject.Name = "Cat";
someObject = myTempObject;
}
public static void Bar(ref MyRefTest someObject)
{
MyRefTest myTempObject = new MyRefTest();
myTempObject.Name = "Cat";
someObject = myTempObject;
}
}
