methuselah methuselah - 10 months ago 82
C# Question

What does `?.` do?

How can I express the following linq query without using

ItemSupplierName = u?.SupplierName

I keep getting a CS1525, CS1003 error message when trying to compile it on my build agent at the above line.

- CS1525 Invalid expression term '.'
- CS1003 Syntax error, ':' expected

Code below, it runs perfectly locally but fails on the build agent.

ExpandedItems = from t in items
from u in t.Supplier.DefaultIfEmpty()
select new {
ItemName = t.Name
ItemSupplierName = u?.SupplierName

Answer Source

The ?. syntax is a new feature in C#6 and is a short cut for checking that the variable isn't null before deferencing it. The fact that you're getting that error on the build server shows that the build server is still running an older version of the compiler.

If you can, get the build agent machine upgraded to use the same version of C# and .NET that you're using to develop with.

If you can't get the build agent upgraded to use the latest version of C# (and .NET) then you'll have to go back to the old way of checking for null:

ItemSupplierName = u != null ? u.SupplierName : null