Question

I have the following expression

int someNumber = somevalue;
ConstantExpression expr = Expression.Constant(someNumber);

Is there a way to check to see if expr < 0 or expr is a negative number ?

Was it helpful?

Solution

If you know the type of the constant, you can simply cast and analyze the underlying constant value.

ConstantExpression expr = /* ... */;
var intConstant = expr.Value as int?;
if (intConstant < 0) { /* do something */ }

Naturally, if all you have is an Expression, you will need to inspect it to determine whether it is a ConstantExpression.

If you don't know the type, but you want to check any valid numeric type:

ConstantExpression expr = /* ... */;

if (expr.Value != null && expr.Value.GetType().IsNumericType()) {
    // Perform an appropriate comparison _somehow_, but not necessarily like this
    // (using Convert makes my skin crawl).
    var decimalValue = Convert.ToDecimal(expr.Value);
    if (decimalValue < 0m) { /* do something */ }
}

Extension methods used in second example:

public static Type GetNonNullableType([NotNull] this Type type)
{
    if (type == null)
        throw new ArgumentNullException("type");

    if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>))
        return type;

    return type.GetGenericArguments()[0];
}

public static bool IsNumericType(this Type type)
{
    if (type == null)
        throw new ArgumentNullException("type");

    type = type.GetNonNullableType();

    if (type.IsEnum)
        return false;

    switch (Type.GetTypeCode(type))
    {
        case TypeCode.SByte:
        case TypeCode.Byte:
        case TypeCode.Int16:
        case TypeCode.UInt16:
        case TypeCode.Int32:
        case TypeCode.UInt32:
        case TypeCode.Int64:
        case TypeCode.UInt64:
        case TypeCode.Single:
        case TypeCode.Double:
        case TypeCode.Decimal:
            return true;
    }

    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top