I would like to implement a method with the following signature
dynamic Cast(object obj, Type castTo);
Anyone know how to do that? obj defi
I think you're confusing the issues of casting and converting here.
It's often hard to know the difference between the 2 in C# because both of them use the same C# operator: the cast.
In this situation you are almost certainly not looking for a cast operation. Casting a dynamic to another dynamic is essentially an identity conversion. It provides no value because you're just getting a dynamic reference back to the same underlying object. The resulting lookup would be no different.
Instead what you appear to want in this scenario is a conversion. That is morphing the underlying object to a different type and accessing the resulting object in a dynamic fashion. The best API for this is Convert.ChangeType.
public static dynamic Convert(dynamic source, Type dest) {
return Convert.ChangeType(source, dest);
}
EDIT
The updated question has the following line:
obj definitely implements castTo
If this is the case then the Cast method doesn't need to exist. The source object can simply be assigned to a dynamic reference.
dynamic d = source;
It sounds like what you're trying to accomplish is to see a particular interface or type in the hierarchy of source through a dynamic reference. That is simply not possible. The resulting dynamic reference will see the implementation object directly. It doesn't look through any particular type in the hierarchy of source. So the idea of casting to a different type in the hierarchy and then back to dynamic is exactly identical to just assigning to dynamic in the first place. It will still point to the same underlying object.