How to express a null coalescence operator using CodeDOM?

Let's say I have a simplified type:

public class Model
{
    public decimal? Result { get; set; }
}

How to express a zero-bound operator using CodeDOM to generate C # code, is it even possible? Now I am using the following workaround:

new CodePropertyReferenceExpression(
    new CodePropertyReferenceExpression(modelArgument, "Result"),
        "Value"))

Which is equal model.Result.Value, but notmodel.Result ?? 0M

The best workaround

CodeExpressionequal model.Result.GetValueOrDefault(0M), suitable for value types with zero value

new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodePropertyReferenceExpression(modelArgument, "Result"),
                            "GetValueOrDefault"),
                            new [] { new CodePrimitiveExpression(0m) })),
+5
source share
1 answer

, ?? - . IL, HasValue, GetValueOrDefault. , , Nullable , Value.

, GetValueOrDefault CodeMethodInvokeExpression, null-coallesing. 4 , , 0m .

new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodePropertyReferenceExpression(modelArgument, "Result"),
                            "GetValueOrDefault"),
                            new [] { new CodePrimitiveExpression(0m) }));

: GetValueOrDefault , HasValue. ( ?? . GetValueOrDefault). :

public T GetValueOrDefault(T defaultValue)
{
  if (!this.HasValue)
    return defaultValue;
  else
    return this.value;
}
+3

All Articles