If so why do c# has pass by reference
C# isn't pass by reference.. it is pass-by-value (unless explicitly using ref
). The value of the reference is copied.
You can think of references as pointers.. with type safety. The underlying implementation detail is of little consequence (although, as I understand it, they currently are a wrapper around a pointer.. but they may not always be).
Pointer variable can be reassigned after initializing, but reference variable cannot be.But I tested this scenario and compiler allows me to re-assign,
There is no restriction on re-assigning a reference like you describe. A new reference will be copied over the top of the existing one. So I'm not sure I understand that issue.
I think your understanding of the above is skewed when passing references through methods. Here is an example:
public class Customer {
public string FirstName { get; set; }
}
public static void Main() {
var customer = new Customer() { FirstName = "Simon" };
Example(customer);
Console.WriteLine(customer.FirstName);
}
public static void Example(Customer customer) {
customer = new Customer() { FirstName = "CHANGED" };
}
(Working example here)
What would this print? The answer is "Simon". The reference was copied into the function. You've re-assigned the local reference. When exiting.. the original reference remains unchanged.
How do you "fix" that? (Not that I would expect the below behaviour..) .. you pass by ref explicitly:
public class Customer {
public string FirstName { get; set; }
}
public static void Main() {
var customer = new Customer() { FirstName = "Simon" };
Example(ref customer); // By ref
Console.WriteLine(customer.FirstName);
}
public static void Example(ref Customer customer) { // By ref
customer = new Customer() { FirstName = "CHANGED" };
}
(Working sample here)
This prints "CHANGED", since the explicit pass-by-ref has been requested by the user of the ref
keyword.