How is it that you can access null nullable’s propery HasValue?
I looked to the compiled code, and it’s not a syntactic sugar.
Why this doesn’t throw NullReferenceException:
int? x = null;
if (x.HasValue)
{...}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That’s because
int?is short forNullable<int>which is a value type, not a reference type – so you will never get aNullReferenceException.The
Nullable<T>struct looks something like this:When you assign
nullthere is some magic happening with support by the compiler (which knows aboutNullable<T>and treats them special in this way) which just sets thehasValuefield to false for this instance – which is then returned by theHasValueproperty.