I’ve read the difference between passng and not passing ref in parameters, however, when would I want to use them?
For example, I had some logic in a method which could be refactored into its own method. Resharper 4.5 made one of the parameters a ref type but I didn’t think I would have of done this if I did the refactoring manually.
Obviously I am missing some understanding. Perhaps an example of what happens when certain types or certain scenarios in coding miss the ref keyword will help?
Thanks
Let me break that down into two questions:
1) When should one use ref/out formal parameter declarations when writing a method?
Use ref/out when you desire your method to be able to read and write a variable passed in from the caller, rather than merely reading a value.
2) Why does an “extract method” refactoring produce a ref parameter?
I don’t know the details of Resharper, but I can make a guess. Consider the following evil mutable value type:
You have a method:
and you do “extract method” on the middle bit:
If instead you made a method without “ref” then calling NewMethod(s) would pass a copy of s to NewMethod. Remember, value types are copied by value; that’s why we called them “value types”. It would be the copy that gets mutated, and then s.X() returns zero. It is a bad idea for a refactoring to introduce a semantic change in a program, and it is difficult for a refactoring engine to know whether a given method relies on the mutability of a value type or not.
This is just another reason why you should avoid mutable value types.