Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition with null in C# 6

Tags:

c#

c#-6.0

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

like image 226
Miguel Moura Avatar asked May 06 '16 16:05

Miguel Moura


3 Answers

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(...);
like image 177
Scott Chamberlain Avatar answered Nov 12 '22 18:11

Scott Chamberlain


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 { ... }
like image 1
CathalMF Avatar answered Nov 12 '22 17:11

CathalMF


Not shorter, but an alternative solution using Linq:

Model m = new Project[] { x.Project }
       .Where(p => p != null)
       .Select(p => new Model { ... })
       .FirstOrDefault();
like image 1
Filipe Borges Avatar answered Nov 12 '22 18:11

Filipe Borges