简体   繁体   中英

C# String interpolation. Use string when decimal? is null

I have the following C$ String interpolation:

decimal? approved = null;

var text = $"new {{ Approved = { approved ?? ""null"" } }}"

In this case, since approved is null, text value should be:

new { Approved = null }

But I get a compilation error:

Operator '??" cannot be applied to operands of type 'decimal?' and 'string'

If I use the following:

var text = "new {{ Approved = { approved } }}"

The text value will become the following which I do not want:

new { Approved = }
decimal? approved = null;
var text = $"new {{ Approved = { (approved?.ToString() ?? "null") } }}";

Both sides of the null coalescing operator ?? need to be of the same type, so call ToString and add the null conditional operator ? to ensure that does not throw an NRE.

The code you posted doesn't compile. You can't do this: var approved = null. To get what you want, you would need to do this:

    decimal? approved = null;
    var text = new { Approved = approved == null ? "null" : approved.ToString() }

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