开发者

Is there a shorthand way to denullify a string in C#?

开发者 https://www.devze.com 2022-12-28 03:35 出处:网络
Is there a shorthand way to denullify a string in C#? It would be the equivalent of (if \'x\' is a string):

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.开发者_JAVA百科ToNotNull();

Any improvements on that, anyone?


This will work:

string y = x ?? "";

See http://msdn.microsoft.com/en-us/library/ms173224.aspx


If you need this reguarly, instead of an extension method you might want to consider creating your own type which behaves like a Nullable and shares the same usage as there is a System.Nullable.GetValueOrDefault(); method. Unfortunately, you can only use System.Nullable on value types so you can't make a nullable string as standard.

0

精彩评论

暂无评论...
验证码 换一张
取 消