Expression.Power C# (CSharp) Method

Power() private static method

private static Power ( string expression, int &index ) : double
expression string
index int
return double
    private static double Power(string expression, ref int index)
    {
        double result = Brackets(expression, ref index);

        while(index < expression.Length)
        {
            if(expression[index] == '^')
            {
                ++index;
                result = Math.Pow(result, Power(expression, ref index));
            }
            else if(expression[index] == '*' && expression[index + 1] == '*')
            {
                index += 2;
                result = Math.Pow(result, Power(expression, ref index));
            }
            else
            {
                break;
            }
        }

        return result;
    }

Usage Example

Example #1
0
        private static void VerifyNullableSBytePower(sbyte?a, sbyte?b)
        {
            Expression <Func <sbyte?> > e =
                Expression.Lambda <Func <sbyte?> >(
                    Expression.Power(
                        Expression.Constant(a, typeof(sbyte?)),
                        Expression.Constant(b, typeof(sbyte?)),
                        typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerSByte")
                        ));
            Func <sbyte?> f = e.Compile();

            // compute with expression tree
            sbyte?    etResult    = default(sbyte);
            Exception etException = null;

            try
            {
                etResult = f();
            }
            catch (Exception ex)
            {
                etException = ex;
            }

            // compute with real IL
            sbyte?    csResult    = default(sbyte);
            Exception csException = null;

            if (a == null || b == null)
            {
                csResult = null;
            }
            else
            {
                try
                {
                    csResult = (sbyte?)Math.Pow((double)a, (double)b);
                }
                catch (Exception ex)
                {
                    csException = ex;
                }
            }

            // either both should have failed the same way or they should both produce the same result
            if (etException != null || csException != null)
            {
                Assert.NotNull(etException);
                Assert.NotNull(csException);
                Assert.Equal(csException.GetType(), etException.GetType());
            }
            else
            {
                Assert.Equal(csResult, etResult);
            }
        }
All Usage Examples Of Expression::Power