Is it OK not to handle returned value of a C# method? What is good practice in this example?

后端 未结 10 2122
南方客
南方客 2020-12-07 23:49

Out of curiosity...what happens when we call a method that returns some value but we don\'t handle/use it? And we also expect that sometimes this returned value could be rea

10条回答
  •  渐次进展
    2020-12-08 00:28

    EDIT: Softened the language very slightly, and clarified.

    It's rarely a good idea to ignore the return value, in my experience - at least in cases where the return values are there to convey new information instead of simply being for convenience.

    One example where I've seen it be okay:

    int foo;
    int.TryParse(someText, out foo);
    
    // Keep going
    

    Here foo will be 0 if either someText contained "0", or it couldn't be parsed. We may not care which was the case in which case the return value of the method is irrelevant to us.

    Another example is in a dictionary - suppose you're trying to count the number of occurrences of each string. You can use:

    int count;
    dictionary.TryGetValue(word, out count);
    dictionary[word] = count + 1;
    

    If the word wasn't in the dictionary to start with, that's equivalent to there being a count of 0 - which is what will already happen as a result of calling TryGetValue.

    As a counter-example, ignoring the value returned by Stream.Read (and assuming that it's managed to read all the data you asked for) is a common mistake.

    If you don't need the return value and it will have taken a lot of effort to compute, it may be worth looking for something which will achieve the same desired side-effects without the extra computation - but there's no extra performance implication. I'd be more worried about the correctness of ignoring a return value than the performance.

    EDIT: Other examples where it's okay to ignore the return value:

    • Some fluent interfaces, including StringBuilder; while StringBuilder.Append(x).Append(y); uses the first return value for the second call, very often the return value of a call will be ignored, e.g. when appending in a loop
    • Some collection calls can give return values which are sometimes ignored - e.g. HashSet.Add which indicates whether the value was actually added, or was already present. Sometimes you just don't care.

    But for the vast majority of the time, ignoring the return value of a method indicates that it's doing more than you need it to.

提交回复
热议问题