Possible Duplicates:
Why use ref keyword when passing an Object?
When to pass ref keyword in
What is the correct usage of the ‘ref’ keyword in C#. I believe there has been plenty of discussion threads on this, but what is not clear to me is:
- Is the ref keyword required if you are passing in a reference object? I mean when you create an object in the heap, is it not always passed by reference. Does this have to be explicitly marked as a ref?
Using
refmeans that the reference is passed to the function.The default behaviour is that the function receives a new reference to the same object. This means if you change the value of the reference (e.g. set it to a new object) then you are no longer pointing to the original, source object. When you pass using
refthen changing the value of the reference changes the source reference – because they are the same thing.Consider this:
Then if you run