Question

How come Nullable<int> can be converted to IFormattable though Nullable<int> not implementing IFormattable

I can confirm that int? type does not implement IFormattable by examining the following code:

var doesImplement = typeof(Nullable<long>).GetInterface(nameof(IFormattable)) != null;

Now that we are sure int? is not IFormattalbe why does the following code works?

int? a = 11111;
var formatted = ((IFormattable)a)?.ToString("N0",null)
// formatted is 11,111

Is there any explicit conversion defined somewhere? If yes, where?

 3  36  3
1 Jan 1970

Solution

 4

(IFormattable)a is a boxing conversion, and it is a bit special, as explained here:

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself. That is, if the HasValue property is true, the contents of the Value property is boxed.

2024-07-22
shingo