简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM