Actually I am doing a list as a reference parameter as follows:
public static List ListMethod(List result)
I saw some people doing in this way too:
public static void ListMethod(ref List result)
If I'm not wrong, "my" method also takes the list
as reference parameter, and you should be able to use it just the same way as "other" does in his method.
But it seems more "clean" to me that you enter a parameter, do something with it and return it in the methods return value.
Any good arguments for or against one method or the other?
Returning the object should be used in most cases because of an optimsation called copy elision. However, depending on how your function is intended to be used, it may be better to pass the object by reference.
C# always returns by value*. However, in C# most types are reference types, which means any variable of that type is a reference; and it is that reference which is returned by value.
Passing value objects by reference is in general a bad design. There are certain scenarios it's valid for, like array position swapping for high performance sorting operations. There are very few reasons you should need this functionality. In C# the usage of the OUT keyword is generally a shortcoming in and of itself.
ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.
It's likely that you don't need to use ref
- but there is a difference.
Usually when I see people using ref
for reference type parameters, it's because they don't understand how parameter passing works. But if your method has something like this:
result = new List();
...
then in the first case the caller won't see the change, whereas in the second case the caller's variable will be changed to refer to the new object.
See my article on parameter passing for a lot more detail.
No, your method does not use a ref
parameter. The default is pass by value
.
The difference is, that your method can just modify the contents of your list but not the reference the parameter result
points to.
Whats the best approach? It depends on what your method is supposed to do.
When your method modifies the list or returns new data you should use the return value. Its much better to understand what your code does than using a ref parameter.
Another benefit of return values is the ability to use method chaining.
You can write code like this which passes the list parameter from one method to another:
ListMethod1(list).ListMethod2(list)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With