简体   繁体   中英

Boxing value type decimal to nullable object?

I unboxed two nullable object ( ie object? ) to decimal and performed some arithmetic on the operands returning a result... (Throwing exceptions if not possible)

How do I box the result back to object? ?

Edit: Code as requested in comment below.

        var baseValue = scope.GetByPath(localPath); //object?
        var rhsValue = Rhs.Execute(scopeIterations); //object?


        decimal res;
        if (baseValue is decimal)
        {
            if (rhsValue is decimal)
            {
                switch (Operator)
                {
                    case ArithmeticOperator.Add:
                        res = ConvertToDecimal(baseValue) + ConvertToDecimal(rhsValue);
                        object? foo = res;
                        break;
                }
            }

So I am getting IDE complaints when boxing res to object? obviously.

This is from a lib:

    private static decimal ConvertToDecimal(object? value)
    {
        if (value != null)
        {
            if (value is string valueAsString)
            {
                return Convert.ToDecimal(valueAsString, (Some CultureInfo);
            }

            return Convert.ToDecimal(value);
        }

        throw new ArgumentNullException(nameof(value));
    }

I am not sure why you would like to do that, there might be better ways.

anyways, you can always cast. Check it here

    int theInt = 8;
    object theObject = theInt;
    int? nullableInt = theInt;

    Console.WriteLine($"{theInt} - {theObject} - {nullableInt}");

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