Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why would a ? appear in IEnumerable<int>?.ToList()? [duplicate]

Tags:

c#

.net

c#-6.0

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?

like image 911
user7242966 Avatar asked Jan 05 '23 20:01

user7242966


1 Answers

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;.

like image 126
rory.ap Avatar answered Jan 11 '23 19:01

rory.ap