Dear All,
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, that the object has been altered when passing control back to the calling object.
Such as this:
class Student
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
class Program
{
static Student student = new Student();
static void Main( string[] args )
{
student.Age = 30;
student.Name = "StudentA";
Console.WriteLine("Original Student: {0}, Age: {1}", student.Name, student.Age);
SetStudent(ref student);
Console.WriteLine("Student by Ref {0}, Age{1}", student.Name, student.Age);
AnotherStudent(student);
Console.WriteLine("Just Another Student {0}, Age {1}", student.Name, student.Age);
Console.ReadLine();
}
public static void SetStudent( ref Student student )
{
student.Age = 16;
student.Name = "StudentY";
}
public static void AnotherStudent( Student studenta )
{
if (studenta.Equals(student))
{
Console.WriteLine("The same object in memory");
}
studenta.Age = 12;
studenta.Name = "StudentX";
}
}
When the student object is passed to AnotherStudent() it gets altered, event thought it is not passed by 'Ref'.
Can someone explain what is happening here?
EDIT
So what is the difference to passing a pointer to an object in C++ in a function?
Tony