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
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.
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