开发者

Using null-coalescing with a property or call method

开发者 https://www.devze.com 2023-02-22 12:58 出处:网络
It is possible to use the ?开发者_运维百科? operation in a situation such this: string str = collection[\"NoRepeate\"] ?? null; // Will not compile

It is possible to use the ?开发者_运维百科? operation in a situation such this:

string str = collection["NoRepeate"] ?? null; // Will not compile 
                          //because collection["NoRepeate"] is object

The problem here is that it is not possible to assign collection["NoRepeate"] which is object to str and collection["NoRepeate"].ToString() throws exception when its value is null.

I'm using now conditional operator ?::

str = collection["NoRepeate"].HasValue ? collection["NoRepeate"].ToString() : null

But the problem is in repeating the constant string.


I agree with you that it is a bit vexing that this cannot be done in a single statement. The null coalescing operator does not help here.

The shortest I am aware of requires two statements.

object obj = collection["NoRepeate"];
string str = obj == null ? null : obj.ToString();


You can do the following:

string str = (string) collection["NoRepeate"] ?? null;

This assumes the object is actually a string though. If it's not, you're going to get a run time error. The other solutions are more robust.

There is no real point in getting this to be as short as possible though. You should make your code readable, not "How short can I write this?"


My solution is:

var field = "NoRepeate";

var str = collection[field].HasValue ? collection[field].ToString() : null;

Of course, if you don't have primitive obsessions you can add a method to the collection class to do this this. Else you'll probably have to stick with an extension method.


Is the object returned from the collection actually a Nullable<object>? Otherwise, you probably want to explicitly check for null:

var item = collection["NoRepeate"];
string str = (item == null) ? null : item.ToString();


Yes that's very possible, if the returned value is null. If the returned value is "" then no. I use it all the time for null values to assign a default.

0

精彩评论

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