Patrick Wambugu
rickwag's blog

rickwag's blog

C#: Demystifying the ref keyword

Photo by Nathan Shively on Unsplash

C#: Demystifying the ref keyword

The ref keyword

Patrick Wambugu's photo
Patrick Wambugu
·Dec 2, 2021·

2 min read

Intro

Have you come across the ref keyword and just completely ignored it? Well here is your chance to get a little more than a peak of what it's all about.

Common Use Cases

Passing a Value type by Reference

You have a string or an integer or any other value type. You want to pass it in a method, modify it in the method and reflect the changes outside the method. What do you do?

ref keyword to the rescue...

string name = "name before";

void SayMyName(ref string nameToSay)
{
    nameToSay = "name after";
}

Console.WriteLine($"name before method call => {name}");

SayMyName(ref name);
Console.WriteLine("......method called..........");

Console.WriteLine($"name after method call => {name}");

//results
//name before method call => name before
//......method called..........       
//name after method call => name after

Attention

For this to work, make sure you use the ref keyword in the method declaration and in the method call

Changing the object pointed at by a variable (of a reference type)

You have created an object from a class and stored its reference in a variable. Now you wanna change the object pointed at by that variable. You begin by trying this...

static void ChangeMyName(Person person)
{
 person = new Person();
 person.Name = "name after";
}
var newPerson = new Person(); 
Console.WriteLine($"before change my name => {newPerson.Name}");

ChangeMyName(newPerson);

Console.WriteLine($"after change my name => {newPerson.Name}");

class Person
{
 public string Name { get; set; } = "name before";
}

//Results
//before change my name => name before
//after change my name => name before

From the results you find out pretty soon that this way doesn't work since the variable(newPerson) still points to the same object in memory.

Now you give this way a try...

static void ChangeMyName(ref Person person)
{
 person = new Person();
 person.Name = "name after";
}

var newPerson = new Person();
Console.WriteLine($"before change my name => {newPerson.Name}");

ChangeMyName(ref newPerson);

Console.WriteLine($"after change my name => {newPerson.Name}");

class Person
{
 public string Name { get; set; } = "name before";
}

//results
//before change my name => name before
//after change my name => name after

You jump up and down congratulating yourself, it worked!!. Now the variable (newPerson) points to another object.

Attention

Similar to how we used the ref keyword before but this time on a reference type.

Conclusion

That's all for now. If you're interested in this topic and wanna dive in tail first, check out the docs here

Thanks😁

 
Share this