Unique ways to use the Null Coalescing operator
I know the standard way of using the Null coalescing operator in C# is to set default values.
string nobody = null;
string somebody = "Bob Saget";
string anybody = "";
anybody = nobody ?? "Mr. T"; // returns Mr. T
anybody = somebody ?? "Mr. T"; // returns "Bob Saget"
But what else can ??
be used for? It doesn't seem as useful as the ternary operator, apart from being more concise and easier to read than:
nobody = null;
anybody = nobody == null ? "Bob Saget" : nobody; // returns Bob Saget
So given that fewer even know about null coalescing operator...
Have you used ??
for something else?
Is ??
necessary, or should you just use the ternary operator (that most are familiar with)
Well, first of all, it's much easier to chain than the standard ternary:
string anybody = parm1 ?? localDefault ?? globalDefault;
vs.
string anyboby = (parm1 != null) ? parm1
: ((localDefault != null) ? localDefault
: globalDefault);
It also works well if null-possible object isn't a variable:
string anybody = Parameters["Name"]
?? Settings["Name"]
?? GlobalSetting["Name"];
vs.
string anybody = (Parameters["Name"] != null ? Parameters["Name"]
: (Settings["Name"] != null) ? Settings["Name"]
: GlobalSetting["Name"];
I've used it as a lazy load one-liner:
public MyClass LazyProp
{
get { return lazyField ?? (lazyField = new MyClass()); }
}
Readable? Decide for yourself.
I've found it useful in two "slightly odd" ways:
out
parameter when writing TryParse
routines (ie return the null value if parsing fails) The latter needs a little bit more information. Typically when you create a comparison with multiple elements, you need to see whether the first part of the comparison (eg age) gives a definitive answer, then the next part (eg name) only if the first part didn't help. Using the null coalescing operator means you can write pretty simple comparisons (whether for ordering or equality). For example, using a couple of helper classes in MiscUtil:
public int Compare(Person p1, Person p2)
{
return PartialComparer.Compare(p1.Age, p2.Age)
?? PartialComparer.Compare(p1.Name, p2.Name)
?? PartialComparer.Compare(p1.Salary, p2.Salary)
?? 0;
}
Admittedly I now have ProjectionComparer in MiscUtil, along with some extensions, which make this kind of thing even easier - but it's still neat.
The same can be done for checking for reference equality (or nullity) at the start of implementing Equals.
链接地址: http://www.djcxy.com/p/57970.html上一篇: 是否存在C#null的Python等价物
下一篇: 使用空合并操作符的独特方法