Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about Explicit operator implementation for Nullable<T> struct

Tags:

c#

.net

I happened to go through the .net framework source code and happened to run across the explicit operator implementation for the Nullable struct implementation. The below screenshots show the implementation of Value property and also the implementation of explicit operator. I also understand that explicit operator is trying to convert from Nullable to T. My question is why is it not that the following code is not throwing an exception

Framework implementation

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

 public static explicit operator T(Nullable<T> value) { 
        return value.Value; 
    }

Custome code

int? i = null;
int? i2 = (int?)i; //No Error

int? i = null;
int i2 = (int)i; //Runtime error

It says value.Value and ideally since HasValue will be false (since I assigned null) it should throw invalid operation exception but it happily assigns the value to i2. However instead of (int?)i if we change it to (int)i the InvalidOperatorException from Value property is being raised. My thought was when value.Value is called it will throw an exception because that property is being accessed and it will do its job.

Please clarify on the same

Thanks,

Sai Pavan

like image 591
usaipavan Avatar asked Dec 28 '25 16:12

usaipavan


1 Answers

Because you cast to int? and not to int

public static explicit operator T(Nullable<T> value) { 
    return value.Value; 
}

T is int but you are casting to int? so Value has never been called.

like image 194
Felix K. Avatar answered Dec 30 '25 04:12

Felix K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!