kaalus
kaalus

Reputation: 4574

Dynamically call user defined conversion operator in C#

Is it possible to dynamically call user defined conversion operators to convert a value to a type?

The method below achieves it by using Expressions, but this is unavailable on platforms which do not support dynamic compilation, like iOS:

static object Cast(object obj, Type t)
{
    var param = Expression.Parameter(obj.GetType());
    return Expression.Lambda(Expression.Convert(param, t), param).Compile().DynamicInvoke(obj);
}

Is there a way that would work without generating code?

Upvotes: 1

Views: 182

Answers (1)

Guru Stron
Guru Stron

Reputation: 142203

You can try using reflection:

var names = new[] {"op_Explicit", "op_Implicit"};
var explicitConversion = obj.GetType()
    .GetMethods()
    .Where(mi => names.Contains(mi.Name) && mi.ReturnType == t) 
    .FirstOrDefault();
return explicitConversion == null
    ? Convert.ChangeType(obj, t)
    : explicitConversion.Invoke(null, new[]{ obj });

Upvotes: 2

Related Questions