? statement in C # does not compile for an unknown reason

In the following code, one of the two options does not compile:

class C
{
    public decimal DecimalField;
}

static C GetC() { return new C(); } //Can return null in reality.

C c = GetC(); //Get a C value from somewhere, this might be null

string toString1 = c?.DecimalField?.ToString(); //Does not compile.
string toString2 = (c?.DecimalField)?.ToString(); //Compiles.

Error CS0023: Operator '?' cannot be applied to a decimal operand

Why can't a simple form compile?

Will the expression c?.DecimalFieldhave a type decimal?? This value can be zero, so the operator must be used ?.. I am sure this is because in this code:

var decimalValue = c?.DecimalField;

varallows decimal?according to IDE.

+4
source share
4 answers

, "". , a?.b.c a null, .b , .c .

, a?.b?.c, , a a.b null. , a.b null. , a.b null, , , .

, a?.b?.c (a?.b)?.c .

# Language Design Meeting, .

+3

decimal . . , null, c null. .

null: (c?.DecimalField)

System.Nullable<decimal> decimal?

+2

, null-coalesce . toString1 .

, DecimalField, NULL, decimal ? insted decimal .

0

.

You can set a default value, it returns DecimalFieldor "0":

string toString = c?.DecimalField.ToString() ?? decimal.Zero.ToString();

Without a default value, it returns DecimalFieldeither null:

string toString = c?.DecimalField.ToString();

Or you can make the DecimalFieldvalue nullable, it returns DecimalFieldeither null:

public decimal? DecimalField;
...
string toString1 = c?.DecimalField?.ToString(); //Compile now!
0
source

Source: https://habr.com/ru/post/1681188/


All Articles