It doesn't do the same thing.. under the hood.
Functionally, it works the same, yes. Under the hood though.. the reference itself is being passed when using ref
. Without ref
, the reference value is copied.
Think of references as memory pointers. student
has the value 1134
.. a memory address. When you don't use ref
, 1134
is applied to a new reference.. pointing at the same memory address.
Using ref
can have dangerous consequences when you realise the above. For example, consider this:
public static void PutLastName(Student student)
{
student = new Student();
student.LastName = "Whitehead";
}
// .. calling code ..
Student st = new Student();
st.FirstName = "Marc";
st.LastName = "Anthony";
PutLastName(st);
Console.WriteLLine(st.FirstName + " " + st.LastName); // "Marc Anthony"
Whereas, using ref
:
public static void PutLastName(ref Student student)
{
student = new Student();
student.FirstName = "Simon";
student.LastName = "Whitehead";
}
// .. calling code ..
Student st = new Student();
st.FirstName = "Marc";
st.LastName = "Anthony";
PutLastName(ref st);
Console.WriteLLine(st.FirstName + " " + st.LastName); // "Simon Whitehead"
Using ref
physically changed the reference. Without it.. you're just telling a different reference to point somewhere else (which is void once the function steps out). So, when using ref
, you're giving the callee the ability to physically change the reference itself.. not just the memory it points at.