null forgiving for Nullable primitive type #5203
-
As null-forgiving documentation, you can use ! to forgiving null value and give a not nullable type. For example class A {
public string? B;
public int? C;
} there is the A class with nullable B and C fields var a = new A();
var b = a.B!; // string
var bNullable = a.B; // Nullable<string>
var c= a.C!; // Nullable<int>
var cNullable = a.C; // Nullable<int> as you can see, the C field always is Nullable, and null forgiving has not worked |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
The null-forgiving operator is by design an operator that only exists at compile time. Transforming |
Beta Was this translation helpful? Give feedback.
-
Hello.
However, |
Beta Was this translation helpful? Give feedback.
Hello.
Nullable<int>
(known asint?
) andint
aren't a same type, so herea.C
you can't use null-forgiving operator!
to declare the not-null state on the propertyC
because you may change the result value from anint?
to anint
. The only way to get the inner value isint value = a.C!.Value
, or also you can use pattern matching:if (a.C is { } value) ...
.However,
string?
andstring
is a same type with different nullability, soa.B!
means the value of the propertyB
is not-null. Therefore the operator can be used on this case.