C# ref Parameters

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 ref parameter must be initialized before it is passed.
  • Overloading can be done when one method has a ref or out parameter and the other has a valueparameter.
  • Can not overload method with one ref other  out. 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 ref or out parameter.
  • Async methods, which you define by using the async modifier can not use ref or out.
  • Iterator methods, which include a yield return or yield break statement can not use ref or out.

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;
}
}