Homam
Homam

Reputation: 23841

Using null-coalescing with a property or call method

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.

Upvotes: 1

Views: 1672

Answers (5)

Scott Wegner
Scott Wegner

Reputation: 7493

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();

Upvotes: 1

Mike Bailey
Mike Bailey

Reputation: 12817

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?"

Upvotes: 2

Timwi
Timwi

Reputation: 66573

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();

Upvotes: 4

kͩeͣmͮpͥ ͩ
kͩeͣmͮpͥ ͩ

Reputation: 7846

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.

Upvotes: 1

jcolebrand
jcolebrand

Reputation: 16025

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.

Upvotes: 0

Related Questions