-1

Generally when we access a property of a object which has a null value, we will face a null exception. But we when we access HasValue property of a Nullable object, it will gives a result. I would like to know what would be implementation behind the sceen.

Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
Sankarann
  • 2,625
  • 4
  • 22
  • 59
  • 5
    The .NET source is [available online](http://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e). – James Thorpe May 12 '16 at 11:36

1 Answers1

0

If you didn't know already, nullable types, like int? are just Nullable<int>.

Nullable types in C# are just a "syntactic sugar". At compile time, the compiler replaces all the int? and double? and bool? with Nullable<int>, Nullable<double> and Nullable<bool>.

Note that Nullable<T> is actually a struct! So technically it can never be null! The reason why you can assign null to a nullable type is yet another syntactic sugar. When you assign null to a nullable type, it sets its HasValue property to false. When you assign a non-null value to it, it sets HasValue to true again and sets the underlying value to the value that you're setting.

That's a brief description of how nullable types works. Now back to your question:

But we when we access HasValue property of a Nullable object, it will gives a result

I guess you mean

But when we access HashValue property of a, say int?, it will never throw an exception, even if the variable is null! Why?

As I said before, Nullable<T> is a struct, so it can never be null. That's why you can access the HasValue property and never throw an exception.

"But why accessing the Value property of a nullable object sometimes throws an exception?" you might ask.

That's because of the implementation of the Nullable<T> struct. As you can see here:

public T Value {
    get {
        if (!hasValue) {
            ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue);
        }
        return value;
    }
}

It checks that if hasValue is true. If it is false, throw an exception.

So that's why.

Sweeper
  • 213,210
  • 22
  • 193
  • 313