If one passes an object to a method using the \'Ref\' keyword then what is the difference with passing it without the ref keyword?
Because both yield the same result, th
Try changing your two Student methods to:
public static void SetStudent( ref Student student )
{
student = new Student();
student.Age = 16;
student.Name = "StudentY";
}
public static void AnotherStudent( Student studenta )
{
studenta = new Student();
studenta.Age = 12;
studenta.Name = "StudentX";
}
The call to SetStudent
will now change your static student variable to reference a new instance because it is passed as a ref
. The call to AnotherStudent
won't change the reference.
Passing by reference allows the method to change the value of the argument passed to the method - so for a reference type, that allows it to change a variable's value to refer to a different object. Here's an example:
using System;
using System.Text;
class Test
{
static void PassByValue(StringBuilder x)
{
x.Append(" - Modified object in method");
x = new StringBuilder("New StringBuilder object");
}
static void PassByReference(ref StringBuilder x)
{
x.Append(" - Modified object in method");
x = new StringBuilder("New StringBuilder object");
}
static void Main()
{
StringBuilder builder = new StringBuilder("Original");
PassByValue(builder);
Console.WriteLine(builder);
builder = new StringBuilder("Original");
PassByReference(ref builder);
Console.WriteLine(builder);
}
}
In both cases, the original StringBuilder
has its contents modified, and then the parameter is assigned a new value. In the "pass by value" case, this doesn't change the value of the builder
variable in Main
. In the "pass by reference" case, the value of builder
refers to the new StringBuilder
, so the results are:
Original - Modified object in method
New StringBuilder object
In your case, you're not seeing any difference with or without ref
because you're not changing the value of the parameter itself - only the data in the object it refers to.
For more information, see my article on parameter passing.