The ref
keyword allows us to pass variables and objects to a method by reference.
ref
with variablesIf a variable is normally passed to a method, its value will be copied into the function for further use. Therefore, altering the value in a method will not affect the value of the original variable.
However, if we pass the variable by reference using ref
, then the original variable will be used in the method.
Note: To use a variable’s reference,
ref
must be written before the variable. Similarly, a reference parameter in a function must haveref
written in its data type.
Here’s a simple example:
class Simple{static void Main(){int num = 10;Simple s = new Simple();s.MultiplyByTwo(num);System.Console.WriteLine("num outside method: " + num);}public void MultiplyByTwo(int num){num = num * 2;System.Console.WriteLine("num inside method: " + num);}}
In the with_ref tab, the MultiplyByTwo
method contains a reference to the num
variable; hence, any modifications in the method will affect the actual variable.
ref
with objectsUnlike variables, the fields/properties of an object are automatically passed by reference, which means that the ref
keyword is not required to alter them.
In the code below, a Superhero
class has been created.
The ChangeHero()
method will modify a Superhero
object’s properties without ref
.
class Program{static void Main(){Superhero hero = new Superhero("Wolverine", "Claws");System.Console.WriteLine(hero.Name + ", " + hero.Power);ChangeHero(hero);System.Console.WriteLine(hero.Name + ", " + hero.Power);// The values of the properties have been changed}public static void ChangeHero(Superhero s){s.Name = "Wonder Woman";s.Power = "Super strength";}}public class Superhero{public Superhero(string n, string p){this.Name = n;this.Power = p;}public string Name {get; set;}public string Power {get; set;}}
So … is there an instance where ref
comes in handy with objects? The answer is yes!
The ref
keyword allows us to change the object that a variable holds. Take a look:
class Program{static void Main(){Superhero hero = new Superhero("Wolverine", "Claws");System.Console.WriteLine(hero.Name + ", " + hero.Power);ChangeHero(ref hero);System.Console.WriteLine(hero.Name + ", " + hero.Power);// The values of the properties have been changed}public static void ChangeHero(ref Superhero s){Superhero newS = new Superhero("Wonder Woman", "Super strength");s = newS; // s now refers to a new object}}public class Superhero{public Superhero(string n, string p){this.Name = n;this.Power = p;}public string Name {get; set;}public string Power {get; set;}}
After the ChangeHero()
method call, the hero
variable refers to a new object that was created within the method. The original object is still in the memory, but there is no way to access it.
ref
is rarely used with objects since there is a possibility of causing memory leaks. Objects can become inaccessible and still occupy space in the memory.
Free Resources