I'm sure I've missed something here. With a certain project I need to check if a string is empty or null.
Is there an easier way of writing this?
if(myString == "" || myString == null)
{
...
I'm sure I've missed something here. With a certain project I need to check if a string is empty or null.
Is there an easier way of writing this?
if(myString == "" || myString == null)
{
...
Or you could take advantage of a quirk in extension methods, they allow this to be null:
which then lets you write:
Although you probably should pick another name than 'empty'.
If you are on .NET 4, you can use
else:
Yes, there's the
String.IsNullOrEmpty
helper method for exactly this already:// if the string is not defined to null then IsNullOrEmpty it works great but if string is defined null then trim will throw exception.
//you can use IsNullOrWhiteSpace which work well for multiple white space in string .i.e it return true for multiple white space also
To avoid null checks you can use ?? operator.
I often use it as guards to avoid sending in data that I don't want in methods.
It can also be used to avoid unwanted formatting.
This can also be used in if statements, it's not so nice but can be handy sometimes.