Best practice: ref parameter or return value?

后端 未结 4 1204
悲哀的现实
悲哀的现实 2020-12-13 11:00

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

相关标签:
4条回答
  • 2020-12-13 11:45

    One thing special about ref Parameter here is that - "A variable passed with ref must be assigned value first.". So if you want to make it strict for the calling method to assign value before the call you can probably use ref Parameters.

    0 讨论(0)
  • 2020-12-13 11:52

    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.

    0 讨论(0)
  • 2020-12-13 11:56

    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)...
    
    0 讨论(0)
  • 2020-12-13 12:00

    If you're just returning a List, you should always use the first one as it shows that intention.

    The version with ref tells me that I can start out with a list, and your method will modify the list I sent in, or even change it with another one. If that is your intention, do that.

    But if the method allways returns a new list, use a return value instead of a ref parameter.

    A note on the side: you could use out instead of ref to show your intentions of returning a new list, but this is only a good practice if you're using the return value for something else.

    0 讨论(0)
提交回复
热议问题