So today I discovered that c# passes reference types by value by default. This ran counter to what I thought I understood – reference types are by reference as standard. Oh well.
This led me to think about a method that I had that took an entity object as a parameter, attached to a context, and made some changes to it. The method did not return the object. When calling save changes on my context, the changes made within the method were applied.
I assumed at the time that it worked because I was passing a reference to the object and so could happily alter it without having to return anything to reassign.
So the question is, how does this work? (the code did work as I expected).
Thanks,
Yes, this stuff is tricky. I’ve found myself not thinking about it for a few months, and then having to think about it for a few seconds to get it straight in my head again. Even though I’ve understood it for a long time.
Even though the parameter is by value, that just means that a new reference variable is created, but still pointing to the same object. If you make the parameter by reference, then the same pointer would be passed in, which of course points to the same object.
It makes a difference when you mess with the parameter variable. If you set it to null or to some other object, the variable “outside” will not be affected. But if the parameter was passed in by value, then setting the variable to null or another object will alter the reference “outside”.
For a value type, whether the parameter is by reference or by value makes a practical difference more often. Changes to the value or to a member (if it’s a struct) will not be reflected “outside” if passed by value.
Here’s a good explanation with easy examples.