Miguel Moura
Miguel Moura

Reputation: 39354

Condition with null in C# 6

I have the following code line:

Project = x.Project == null ? null : new Model { ... }

Is there any way, in C# 6, to make this code shorter?

I have a been looking at a few ? examples but for this case I can't find a shorter solution ...

Upvotes: 10

Views: 959

Answers (3)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

As-is your code is as short as it possibly can be. However if the class Project is based on had a public Model ToModel(...) { } method you could do

Project = x.Project?.ToModel(...);

UPDATE: As JonSkeet just mentioned, you could also make .ToModel( a extension method.

public static class ExtensionMethods
{
    public static Model ToModel(this Project p, ...)
    {
        return new Model { ... };
    }
}

The syntax would still be

Project = x.Project?.ToModel(...);

Upvotes: 10

Filipe Borges
Filipe Borges

Reputation: 2783

Not shorter, but an alternative solution using Linq:

Model m = new Project[] { x.Project }
       .Where(p => p != null)
       .Select(p => new Model { ... })
       .FirstOrDefault();

Upvotes: 1

CathalMF
CathalMF

Reputation: 10055

No, Its as short as you can make it.

However based on this code you should actually have an if condition above it to check the value of x

if(x != null)
    Project = x.Project == null ? null : new Model { ... }
else
    Project = null;

You can change this to :

Project = x?.Project == null ? null : new Model { ... }

Upvotes: 1

Related Questions