Is there a shorthand way to denullify a string in C#?
It would be the equivalent of (if 'x' is a string):
string y = x == null ? "" : x;
I guess I'm hoping there's some operator that would work something like:
string y = #x;
Wishful thinking, huh?
The closest I've got so far is an extension method on the string class:
public static string ToNotNull(this string value)
{
return value == null ? "" : value;
}
which allows me to do:
string y = x.ToNotNull();
Any improvements on that, anyone?
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
The null-coalescing operator ( ?? ) is like a shorthand, inline if/else statement that handles null values. This operator evaluates a reference value and, when found non-null, returns that value. When that reference is null , then the operator returns another, default value instead.
C# | IsNullOrEmpty() Method It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String. Empty (A constant for empty strings).
This will work:
string y = x ?? "";
See http://msdn.microsoft.com/en-us/library/ms173224.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With