2

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?

amiry jd
  • 27,021
  • 30
  • 116
  • 215
JuanDYB
  • 590
  • 3
  • 9
  • 23

2 Answers2

8

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

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
4

This works because int can be implicitly converted to a decimal, and therefore the nullable versions can also be implicitly converted.

FROM   TO
int    long , float, double, or decimal

https://msdn.microsoft.com/en-us/library/y5b434w4.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/06/27/what-exactly-does-lifted-mean.aspx

Eric J.
  • 147,927
  • 63
  • 340
  • 553