I usually use something like this for various reasons throughout an application:
if (String.IsNullOrEmpty(strFoo))
{
FooTextBox.Text = \"0\";
}
else
{
You can write your own Extension method for type String :-
public static string NonBlankValueOf(this string source)
{
return (string.IsNullOrEmpty(source)) ? "0" : source;
}
Now you can use it like with any string type
FooTextBox.Text = strFoo.NonBlankValueOf();
This may help:
public string NonBlankValueOf(string strTestString)
{
return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}
There is a null coalescing operator (??
), but it would not handle empty strings.
If you were only interested in dealing with null strings, you would use it like
string output = somePossiblyNullString ?? "0";
For your need specifically, there is the conditional operator bool expr ? true_value : false_value
that you can use to simplify if/else statement blocks that set or return a value.
string output = string.IsNullOrEmpty(someString) ? "0" : someString;
Old question, but thought I'd add this to help out,
#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif
You could use the ternary operator:
return string.IsNullOrEmpty(strTestString) ? "0" : strTestString
FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
You can achieve this with pattern matching with the switch expression in C#8/9
FooTextBox.Text = strFoo switch
{
{ Length: >0 } s => s, // If the length of the string is greater than 0
_ => "0" // Anything else
};