It does not do the same ... under the hood.
Functionally, it works the same way, yes. Under the hood, though .. the link itself is passed when using ref . Without ref reference value is copied.
Think of references as pointers to memory. student has a value of 1134 .. memory address. If you are not using ref , 1134 applies to the new link. By specifying the same memory address.
Using ref can have dangerous consequences when you understand above. For example, consider the following:
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"
While 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 link. Without this .. you just say another link to point somewhere else (which is not valid after exiting the function). Thus, when using ref you give the called party the ability to physically change the link itself ... not just the memory that it points to.
Simon whitehead
source share