I have a class Thing
that is implicitly castable from a string
. When I call a method with a Thing
parameter directly the cast from s
In this specific case you can make the conversion through the array type, that is
showThingReflected.Invoke(this, new Thing[] {"foo"});
but that's a kind of "cheating". In general, you cannot expect the Invoke
to consider your user-defined implicit operator
. This conversion must be inferred compile-time.
Found an answer which uses a TypeConverter (as Saeed mentions)
Seems to do the job.
TypeConverter For Implicit Conversion when using reflection
The trick is to realize that the compiler creates a special static method called op_Implicit
for your implicit conversion operator.
object arg = "foo";
// Program.showThing(Thing t)
var showThingReflected = GetType().GetMethod("showThing");
// typeof(Thing)
var paramType = showThingReflected.GetParameters()
.Single()
.ParameterType;
// Thing.implicit operator Thing(string s)
var converter = paramType.GetMethod("op_Implicit", new[] { arg.GetType() });
if (converter != null)
arg = converter.Invoke(null, new[] { arg }); // Converter exists: arg = (Thing)"foo";
// showThing(arg)
showThingReflected.Invoke(this, new[] { arg });