Concatenated string in IsNullOrEmpty parameter

I watched the code snippet that I wrote in C #:

if(string.IsNullOrEmpty(param1) && string.IsNullOrEmpty(param2) && string.IsNullOrEmpty(param3)) { // do stuff } 

and decided to make it more understandable / concise

 if(string.IsNullOrEmpty(param1+param2+param3)) { // do stuff } 

But looking at him, I cannot help but cringe. What do you think about this? Have you ever done something like this, and do you use it when applicable.

Note. The code preceding this line will manipulate the collection by adding certain elements depending on whether the parameter a (param1, param2, param3) is NOT empty. This if statement is for error checking / handling.

+4
source share
6 answers

Personally, I prefer the former over the latter. For me, the intention is more explicit - checking if all parameters are empty / empty.

The second also hides the fact that it processes zeros. Zero lines are odd. For example, Jason Williams, for example, did not realize that he really works.

+5
source

Maybe write something like this, which is a bit readable:

 bool paramsAreInvalid = string.IsNullOrEmpty(param1) && string.IsNullOrEmpty(param2) && string.IsNullOrEmpty(param3); if (paramsAreInvalid) { // do stuff } 
+4
source

This is a small thing, but I think that a little reformatting of your original results in improved readability makes the goal of the code about as transparent as possible:

 if ( string.IsNullOrEmpty(param1) && string.IsNullOrEmpty(param2) && string.IsNullOrEmpty(param3) ) { // do stuff } 

Consider a similar set of examples:

 if ( c == 's' || c == 'o' || c == 'm' || c == 'e' || c == 't' || c == 'h' || c == 'i' || c == 'n' || c == 'g') { // ... } if ( c == 's' || c == 'o' || c == 'm' || c == 'e' || c == 't' || c == 'h' || c == 'i' || c == 'n' || c == 'g') { // ... } 
+3
source

This will not work. If any of the lines is NULL, you will get a null difference exception. You need to check them before using them.

In addition, it is very inefficient. You concatenate all the lines into a new line, then check to see if it is empty. This results in one or more memory allocations and potentially large amounts of data to be copied, which must be immediately discarded and garbage collected in a minute.

The best approach is to write a method that takes variable arguments or a list of strings and checks them one by one using IsNullOrEmpty in a loop. It will be more efficient, safer, but the desired result of accurate code in your if statement will still be achieved.

+2
source

If you can get the parameters in the collection (which, if it works with the params ), it might work:

 if (myParams.Any(IsNullOrTrimEmpty) { // do stuff } 

This example uses this string extension , and myParams string[] .

+1
source

The source code, although longer, is clearer in its intent and is likely similar in performance. I would leave it alone.

0
source

All Articles