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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With