1

Can someone explain how the below statement operates. I know that the ?? operator returns the first argument if it is not null. But I was a little confused when I saw the ? following the 'file' variable.

return file?.ImportStatus ?? ImportStatusEnum.Unknown;
jengfad
  • 704
  • 2
  • 8
  • 20

3 Answers3

9

This is a combination of null propagation and null coalesce operators.

It will produce ImportStatusEnum.Unknown in the following cases:

  • file is null - In this case, .ImportStatus is not evaluated, and the left side of ?? becomes null, or
  • file is not null, but ImportStatus is null - in this case, the left side of ?? is also null, so the right side is used.

If neither file nor its ImportStatus are null, then the value of file.ImportStatus will be used as the result of the overall expression.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
5

@dasblinkenlight is correct, just to show it a different way, it could be written like this (in order of evaluation):

if (file == null) return ImportStatusEnum.Unknown;
if (file.ImportStatus  != null) 
    return file.ImportStatus;
else 
    return ImportStatusEnum.Unknown;
garethb
  • 3,951
  • 6
  • 32
  • 52
1

Actually, the compiler will generate different code based on whether the ImportStatus is nullable or not. If it is NOT nullable, so like this:

public ImportStatusEnum ImportStatus {get; set;}

then the compiler will generate this:

return file != null ? file.ImportStatus : ImportStatusEnum.Unknown;

which is the same as

if (file != null)
    return file.ImportStatus;
return ImportStatusEnum.Unknown;

If the property is nullable, so like this:

public ImportStatusEnum? ImportStatus {get; set;}
//OR
public Nullable<ImportStatusEnum> ImportStatus {get; set;}

then it will do what @dasblinkenlight and @garethb have indicated in their answers.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64