Example #1
0
 private void CoerceTypes(string operatorName, ref Expression leftExpr, ref Expression rightExpr)
 {
     if (leftExpr.Type != rightExpr.Type)
     {
         var leftType  = TypeFns.GetNonNullableType(leftExpr.Type);
         var rightType = TypeFns.GetNonNullableType(rightExpr.Type);
         if (leftType == typeof(String))
         {
             ConvertExpr(ref rightExpr, ref leftExpr);
         }
         else if (rightType == typeof(String))
         {
             ConvertExpr(ref leftExpr, ref rightExpr);
         }
         else if ((TypeFns.IsNumericType(leftType) || TypeFns.IsEnumType(leftType)) && (TypeFns.IsNumericType(rightType) || TypeFns.IsEnumType(rightType)))
         {
             var leftIx  = NumericTypes.IndexOf(leftType);
             var rightIx = NumericTypes.IndexOf(rightType);
             if (leftIx < rightIx)
             {
                 ConvertExpr(ref leftExpr, ref rightExpr);
             }
             else
             {
                 ConvertExpr(ref rightExpr, ref leftExpr);
             }
         }
         else if (leftType == typeof(Guid) ||
                  leftType == typeof(DateTime) ||
                  leftType == typeof(Boolean) ||
                  leftType == typeof(TimeSpan) ||
                  TypeFns.IsNumericType(leftType) ||
                  TypeFns.IsEnumType(leftType))
         {
             ConvertExpr(ref rightExpr, ref leftExpr);
         }
         else
         {
             throw new Exception("Unable to perform operation: " + operatorName + "on types:"
                                 + leftExpr.Type + ", " + rightExpr.Type);
         }
     }
 }
Example #2
0
        // coerce fromExpr to toExpr type
        // but also convert both to nonnullable types.
        private void ConvertExpr(ref Expression fromExpr, ref Expression toExpr)
        {
            var constExpr = fromExpr as ConstantExpression;

            var toType = TypeFns.GetNonNullableType(toExpr.Type);

            if (constExpr != null)
            {
                if (constExpr.Value == null)
                {
                    return;
                }
                var newValue = Convert.ChangeType(constExpr.Value, toType);
                fromExpr = Expression.Constant(newValue);
            }
            else
            {
                fromExpr = Expression.Convert(fromExpr, toType);
            }
            if (TypeFns.IsNullableType(toExpr.Type))
            {
                toExpr = Expression.Convert(toExpr, toType);
            }
        }