Is there an easier way to do this in C#? (null-coalescing type question)
Is there an easier way to do this?
string s = i["property"] != null ? "none" : i["property"].ToString();
notice the difference between it and null-c开发者_JS百科oalesce (??) is that the not-null value (first operand of ?? op) is accessed before returning.
Try the following
string s = (i["property"] ?? "none").ToString();
If indexer returns object
:
(i["property"] ?? (object)"none").ToString()
or just:
(i["property"] ?? "none").ToString()
If string
:
i["property"] ?? "none"
Alternatives for fun.
void Main()
{
string s1 = "foo";
string s2 = null;
Console.WriteLine(s1.Coalesce("none"));
Console.WriteLine(s2.Coalesce("none"));
var coalescer = new Coalescer<string>("none");
Console.WriteLine(coalescer.Coalesce(s1));
Console.WriteLine(coalescer.Coalesce(s2));
}
public class Coalescer<T>
{
T _def;
public Coalescer(T def) { _def = def; }
public T Coalesce(T s) { return s == null ? _def : s; }
}
public static class CoalesceExtension
{
public static string Coalesce(this string s, string def) { return s ?? def; }
}
精彩评论