I was making a program in which I want to check if a string is equal to ""
, and if it isn't use it, but if it is, use the default value. I know I can do string != "" ? string : "default value"
, however, I feel like this is inefficient, as I keep typing out string
. Of course, writing out string
is no problem for me, but, if in another project, I have to reference a string with a long package name, it would be a little more annoying.
According to DavidG's option and helpful link, you could use this extension function.
public static string IfEmpty(this string str, string alternate)
{
return str?.Length == 0 ? str : alternate;
}
(This will return the alternate string even if the 'str' is null)
And use as mystring.IfEmpty("something else")
Source: What is the difference between String.Empty and "" (empty string)?.
Also you don't need to reference a really long string.