DEV Community

Siddhant Patra
Siddhant Patra

Posted on

1 1

Understanding the ref keyword in C#

I have seen many newbies getting confused with the meaning and significance of the ref keyword in C#.
Instead of talking I would like to show the use of ref keyword in some simple examples.

using System;
public class Program
{
public static void Main()
{
var nameEnt = new NameEntity()
{
Name = "Outer"
};
Console.WriteLine(nameEnt.Name); // "Outer"
EntityModifier(nameEnt);
Console.WriteLine(nameEnt.Name); // "Outer"
EntityRefModifier(ref nameEnt);
Console.WriteLine(nameEnt.Name); // "Inner"
Console.WriteLine();
}
public static void EntityModifier(NameEntity nameEnt) // creates a copy of the address hash of the object
{
nameEnt = new NameEntity
{
Name = "Inner"
};
}
public static void EntityRefModifier(ref NameEntity nameEnt) // the pointer to the variable containing
// the address hash of the object is passes as an argument
{
nameEnt = new NameEntity
{
Name = "Inner"
};
}
}
public class NameEntity {
public string Name;
}

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay