Check a string for nothing and then for a specific value in 1 line?

I seem to always see if the string (querystring value) has a value, but first I have to check that this is not the first time, so I end up with 2, if it does, I don't see anything like it here. this is the best way to do it:

If Not String.IsNullOrEmpty(myString) Then
  If CBool(myString) Then
   //code
   End If
End If

      

+1


source to share


5 answers


In VB.Net, and does not short circuit, but AndAlso does.

(same for Or and OrElse)



So your code should look something like this:

If Not String.IsNullOrEmpty(myString) AndAlso CBool(myString) Then 
    ....
End If

      

+4


source


The logical operator "and" in your language of choice? Legends are usually short-circuited, so if the first one doesn't work, the second one won't work / error.



+1


source


AndAlso (as mentioned) is the most versatile answer. But you can also use various TryParse methods that will do the code like this:

Dim b as Boolean
If Boolean.TryParse(myString, b) AndAlso b Then
End If

      

Bonus, it will save you a FormatException when someone sends "blah" to your request.

+1


source


FYI this type of code is ideal as an "extension method". In short, this means that you can expand the string with a method that provides your own code.

Take a look :)

0


source


Use if using .NET 2.0 or higher:

String.IsNullOrEmpty(thestringobject)

      

Will evaluate to True or False. I usually create another function in the Utility class that does this check and also checks for trim / length, so I know if the string object is null, empty, or empty space.

0


source







All Articles