Reputation: 165
Appreciate there have been some question close to what I am asking but not quite like here. I have been checking the ?. operator and I came upon the following scenario. Situation is as follows:
internal class Dog
{
public int? Age { get; set; }
}
Checks in main code were as follows:
Dog d2 = new Dog() { Age = 10 };
int age1 = d2.Age.Value; // compiles okay
int age2 = d2?.Age.Value; // CS0266
I would like to know why the code line with age3 is requesting an explicit cast. d2.Age being type int? and Age.Value being type int doesn't vary between the two usages.
Upvotes: 0
Views: 276
Reputation: 14856
Once you use the null-condicional operator, the resulting value can be null
. that's why it can never be int
.
What you need is:
int age2 = (d2?.Age).Value;
Upvotes: 2