This is pretty tricky. The problem is that var
does not mean "variant". It is acts more like a temporary placeholder that C# fills in with an actual type once the type information can be inferred from the expression. unboxedData
is still very much a strongly typed variable. Its just the compiler is trying to figure out the type instead of you explicitly specifying it. It is is of vital importance to note that the typing is still occurring at compile time and not runtime.
If you want to dynamically cast an object at runtime then you will not be able to use var
or any other concrete type specifier.
Your options are limited to one of the two possible declarations:
Based on what I think you want to do with unboxedData
I suspect dynamic
is the route you want to go because it would allow you to call any method on the target Type
.
So here is what I came up with.
public void FooBar(object value, Type expected)
{
dynamic unboxedData = expected.FromObject(value);
unboxedData.CallSomeMethodDefinedInTheTargetType(); // This will work.
}
This requires the following extension method.
public static class TypeExtension
{
public static object FromObject(this Type target, object value)
{
var convertable = value as IConvertible;
if (convertable != null)
{
return convertable.ToType(target, null);
}
Type type = value.GetType();
if (target.IsAssignableFrom(type))
{
return value;
}
MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo mi in methods)
{
if (mi.ReturnType == target)
{
try
{
return mi.Invoke(null, new object[] { value });
}
catch (TargetInvocationException caught)
{
if (caught.InnerException != null)
{
throw caught.InnerException;
}
throw;
}
}
}
throw new InvalidCastException();
}
}
The cast will work if one of the following are true.
- The value to be converted implements
IConvertible
and has a conversion path to the target type.
- The value to be converted subclasses the target type.
- The value to be converted defines an explicit conversion operator in its class declaration.