Saturday, January 29, 2011

Dynamic casting in c#

var typesSubset = new[] { typeof(decimal), typeof(Int32), typeof(Int64) };

Type someDynamicType = typeof (int);

int someDynamicValue = 777;

if (typesSubset.Any(t => t == someDynamicType))

{

    object result = Expression.Lambda<Func<object>>(

        Expression.Convert(Expression.Add(

                               Expression.Constant(someDynamicType), Expression.Constant(someDynamicValue)),

                           typeof (object))).Compile()();

 

    Console.WriteLine(result); // 777

}

No comments: