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)