If array is null , attempting to eliminate array.Length will NullReferenceException . If your code considers null invalid value for array , you must reject it and blame the caller. One of these patterns is to throw an ArgumentNullException :
void MyMethod(string[] array) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Length > 0) {
If you want to accept the null array as an indication not to do anything or as an optional parameter, you can simply not access it if it is null:
void MyMethod(string[] array) { if (array != null) {
If you want to not touch array when it is either null or has zero length, then you can check both at the same time as C # -6s operator with zero coalescence .
void MyMethod(string[] array) { if (array?.Length > 0) {
Excess length check
It seems strange that you are treating an empty array as a special case. In many cases, if you, for example, just go through the array anyway, there is no need to consider an empty array as a special case. foreach (var elem in array) {«body»} just won't execute «body» when array.Length is 0 . If you are referring to array == null || array.Length == 0 array == null || array.Length == 0 specifically, for example, to improve performance, you can leave a comment for posterity. Otherwise, checking for Length == 0 seems unnecessary.
Redundant code complicates the understanding of the program, because people reading the code supposedly assume that each line is necessary to solve a problem or achieve correctness. If you include unnecessary code, readers are going to spend forever trying to figure out why this line was or was needed before deleting it; -).
binki Jun 27 '17 at 21:52 2017-06-27 21:52
source share