What is the easiest way to verify that a string is not null, not empty, and not = "0000"?

I used the following:

!string.IsNullOrEmpty(Model.ProductID) 

But now I need to check also that the line is not equal to "0000". What is the easiest way to do this check?

+4
source share
5 answers
 !string.IsNullOrEmpty(Model.ProductID) && Model.ProductID != "0000" 

or write an extension method:

 public static class StringExtensions { public static bool IsNullEmptyOrZeros(this string value) { return !string.IsNullOrEmpty(value) && value != "0000"; } } 

and then:

 if (!Model.ProductID.IsNullEmptyOrZeros()) { ... } 
+9
source
 if(!string.isNullOrEmpty(Model.ProductID) && Model.ProductID != "0000") 
+1
source

What about...

 if (!string.IsNullOrEmpty(Model.ProductID) && Model.ProductID.Trim() != "0000") 

I really don't think there is a feature for your specific case. Not very often people want to check the string for all three of these conditions.

And there is no reason to worry about “optimizing” this code anyway. The && operator is short-circuited, which means that string comparisons will not even happen if the string does not contain some value.

0
source

In addition to the IsNullOrEmpty tag IsNullOrEmpty add a test for string.Trim('0').Length != 0 . It will also catch strings that represent any number of zeros (instead of specifically 4).

0
source

I think you also need to check if the value is ""

If in C # 4.0 you should use

 !string.IsNullOrWhiteSpace(Model.ProductID) && Model.ProductID != "0000" 

Or not,

 !string.IsNullOrEmpty(value) && value.trim().length > 0 && Model.ProductID != "0000" 
0
source

Source: https://habr.com/ru/post/1386920/


All Articles