Search code examples
c#decimalnullable

C# Is nullable int descendant of nullable decimal


I have discovered by error something that surprised me.

I have this method

public static string PrintDecimal(decimal? input, string NumberFormat = null){ }

And I call this method like this

int? MaxFaltas = 0;
Label.Text = CustomConvert.PrintDecimal(MaxFaltas);

Why this is working and there are no compilation errors. I'm calling a method witch is defined to receive a decimal? with a int?


Solution

  • You just discovered something described in the spec as lifted operators.

    They let you convert Nullablt<A> to Nullable<B> as long as A can be converted to B.

    6.4.2 Lifted conversion operators

    Given a user-defined conversion operator that converts from a non-nullable value type S to a non-nullable value type T, a lifted conversion operator exists that converts from S? to T?. This lifted conversion operator performs an unwrapping from S? to S followed by the user-defined conversion from S to T followed by a wrapping from T to T?, except that a null valued S? converts directly to a null valued T?.