4

I was reviewing some code and I came across the following line of code:

List authorIntList = authorIds?.ToList();

In the example above, authorIds is an IEnumerable. What is the purpose of the ? in the line of code above? I'm not sure I've ever seen this pattern before. What does it do and in which version of .NET was it implemented?

Yoopergeek
  • 5,592
  • 3
  • 24
  • 29
user7242966
  • 347
  • 1
  • 10

4 Answers4

11

That's called the "null conditional operator" -- i.e. ? and . together -- new to C# 6.0. What it means is that, if authorIds is not null, then it will call/return ToList() on it. Otherwise, it will return null. It's basically syntactic sugar so you don't have to write lengthier code like List AuthorIntList = authorIds != null ? authorIds.ToList() : null;.

rory.ap
  • 34,009
  • 10
  • 83
  • 174
0

The "Null Conditional Operator" exists as a way to shorthand "If this isn't null, do the thing, otherwise return null". It's basically the same as

List authorIntList = authorIds ? authorIDs.ToList() : null; //null coalescing

or

List authorIntList = null;
if(authorIDs != null) { authorIntList = authorIDs.ToList(); } //traditional if
CDove
  • 1,940
  • 10
  • 19
0

It is a null conditional operator that in many languages people call it Elvis operator. It has been added from c# 6.0 and checks your code with null.

So if you have something like:

var x= a?.b?.c?.d;

x will be null if any of a,b,c or d be null. and it will be the value in d if all of them are not null. before you had to put them in if conditions.

if(a!= null && a.b!= null && a.b.c!= null)
{
    x= a?.b?.c?.d;
}
Ashkan S
  • 10,464
  • 6
  • 51
  • 80
  • Not Elvis. See comments under Woot's answer. – rory.ap Dec 30 '16 at 16:31
  • @rory.ap I've already wrote that it is called null conditional . in the c# 6.0 introduction in mva.microsoft.com they've mentioned the name Elvis for it but they wasn't sure that they are going to use that name. – Ashkan S Dec 30 '16 at 16:35
-1

Correction Null Conditional operator https://msdn.microsoft.com/en-us/library/dn986595.aspx

It's like saying if authorId's is not null then execute ToList() else returns null.

Woot
  • 1,759
  • 1
  • 16
  • 23