.netbyrefbyval

Best Practice: ByRef or ByVal? in .Net


What are the things to consider when choosing between ByRef and ByVal.

I understand the difference between the two but I don't fully understand if ByRef saves resources or if we even need to worry about that in the .Net environment.

How do you decide between the two if the functionality doesn't matter in a situation?


Solution

  • There's a lot of misinformation around about this. The main thing is that you understand the difference between value types and reference types, and the difference between pass by value and pass by reference.

    You almost always want to pass by value. Passing by reference is almost always for "I want to return more than one result, and not just by adding things to a list which is passed in." The classic example of a method using pass-by-reference is Int32.TryParse where the return value is a success/failure, and the parsed value is "returned" by an out parameter.