Program receiving and outputting data Operator types

In C #, given two Type

s inputs , is it possible to define an output Type

and an implicit upcast Type

for the operator? For example, consider an expression s + i

. Let's say I have the following information:

short s;
int i;
Type leftType = typeof(short);
Type rightType = typeof(int);

      

Can I define the following information about the expression s + i

?

Type leftUpcastType = typeof(int);
Type rightUpcastType = typeof(int);
Type outputType = typeof(int);

      

I could obviously do it with a huge lookup table of all types and operators, but it could be easier. Ideally, this will work for custom classes with operator overloads, but this is a secondary requirement.

+3


source to share


2 answers


Yes, you can achieve this using type dynamic

. Keep in mind that this dynamic throws an exception for anything that cannot be summed at runtime, so you will need to make sure you only pass in valid values ​​or end up with a / catch.

var leftType = left.GetType();
var rightType = right.GetType();
var outputType = ((dynamic)left + (dynamic)right).GetType();

      



You can then infer from this information whether one, both, or none of the objects have been converted for the operation.

+2


source


The best way to do this is to check the type of the return expression, which adds two values ​​of the types you are interested in. This way you don't have to worry about providing valid values ​​to add at runtime when all you care about is the return type.

You can either take an existing expression, or go down the expression tree if available to you, or do something like this:

static Type GetTypeOfSummation<T1, T2>()
{
    var p1 = Expression.Parameter(typeof(T1), "t1");
    var p2 = Expression.Parameter(typeof(T2), "t2");

    LambdaExpression x = DynamicExpression.ParseLambda(new[] { p1, p2 }, null, "t1 + t2");
    return x.Body.Type;
}

static void Main()
{
    Console.WriteLine(GetTypeOfSummation<int, double>());   // System.Double
    Console.WriteLine(GetTypeOfSummation<int, decimal>());  // System.Decimal
    Console.WriteLine(GetTypeOfSummation<float, double>()); // System.Double
}

      

This generic method will return the type of the add operation without actually performing the add.



You can, of course, do this using instances Type

instead of type type parameters if you need to:

static Type GetTypeOfSummation(Type t1, Type t2)
{
    var p1 = Expression.Parameter(t1, "t1");
    var p2 = Expression.Parameter(t2, "t2");

    LambdaExpression x = DynamicExpression.ParseLambda(new[] { p1, p2 }, null, "t1 + t2");
    return x.Body.Type;
}

      

To be clear, DynamicExpression

from the namespace System.Linq.Dynamic

you can get by referencing: https://www.nuget.org/packages/System.Linq.Dynamic/

+2


source







All Articles