Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value or null of nullable variable

Tags:

c#

c#-6.0

With C# 6 I have the following model:

public class Model {
  public Int32? Result { get; set; }
}

And I have the following (example code):

Model model = new Model();     
Int32 result = model.Result.Value;

If Result is null I get an error so I need to use:

Int32 result = model.Result.HasValue ? model.Result.Value : 0;

Is there a shorter way to do this in C# 6?

like image 940
Miguel Moura Avatar asked May 09 '16 18:05

Miguel Moura


1 Answers

You can use the null-propagating operator with the null conditional operator to provide a default value.

Model modelWithNullValue = new Model();
Model modelWithValue = new Model { Result = 1};
Model modelThatIsNull = null;
Int32 resultWithNullValue = modelWithNullValue?.Result ?? -1;
Int32 resultWithValue = modelWithValue?.Result ?? -1;
Int32 resultWithNullModel = modelThatIsNull?.Result ?? -2;
Console.WriteLine(resultWithNullValue); // Prints -1
Console.WriteLine(resultWithValue); // Prints 1
Console.WriteLine(resultWithNullModel); // Prints -2

Edit: As of C# 7.2, the following syntax is also valid for setting a default value in this kind of situation.

Model badModel = null;
var result = badModel?.Result ?? default;
var pre72 = badModel?.Result ?? default(int);
Console.WriteLine(result); // 0
Console.WriteLine(result.GetType().Name); // Int32
like image 145
Jonathon Chase Avatar answered Oct 24 '22 06:10

Jonathon Chase