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
orout
parameter and the other has avalue
parameter. - Can not overload method with one
ref
otherout
. 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
orout
parameter. Async
methods, which you define by using theasync
modifier can not useref
orout
.- Iterator methods, which include a yield return or yield break statement can not use
ref
orout
.
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; } }