Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

.net - C# if-null-then-null expression

Just for curiosity/convenience: C# provides two cool conditional expression features I know of:

string trimmed = (input == null) ? null : input.Trim();

and

string trimmed = (input ?? "").Trim();

I miss another such expression for a situation I face very often:

If the input reference is null, then the output should be null. Otherwise, the output should be the outcome of accessing a method or property of the input object.

I have done exactly that in my first example, but (input == null) ? null : input.Trim() is quite verbose and unreadable.

Is there another conditional expression for this case, or can I use the ?? operator elegantly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like Groovy's null-safe dereferencing operator?

string zipCode = customer?.Address?.ZipCode;

I gather that the C# team has looked at this and found that it's not as simple to design elegantly as one might expect... although I haven't heard about the details of the problems.

I don't believe there's any such thing in the language at the moment, I'm afraid... and I haven't heard of any plans for it, although that's not to say it won't happen at some point.

EDIT: It's now going to be part of C# 6, as the "null-conditional operator".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...