In .net (C#), If you have two types discovered through reflection is it possible to determine if one can be cast to the other? (implicit and/or explicit).
What I'm trying to do is create a library that allows users to specify that a property on one type is mapped to a property on another type. Everything is fine if the two properties have matching types, but I'd like to be able to allow them to map properties where an implicit/explicit cast is available. So if they have
class from
{
public int IntProp{get;set;}
}
class to
{
public long LongProp{get;set;}
public DateTime DateTimeProp{get;set;}
}
they would be able to say that from.IntProp will be assigned to to.LongProp (as an implicity cast exists). But if they said that it mapped to DateTimeProp I'd be able to determine that there's no available cast and throw an exception.
This should do the trick for implicit and explicit conversions (including numeric types, classes, etc.)
So, probably you mean duck typing or structural typing? There are several implementations that will dynamically generate the required proxies.
For example:
http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx
It would be better to look into TypeConverter's.
To directly answer your question ...
... you can use something similar to this :
The Type.IsAssignableFrom() method can be used for exactly your purpose. This would also be considerably less verbose (even if only marginally more performant) than using TypeConverters.
Here's an implementation isn't pretty but which I believe covers all cases (implicit/explicit operators, nullable boxing/unboxing, primitive type conversions, standard casts). Note that there's a difference between saying that a conversion MIGHT succeed vs. that it WILL succeed (which is almost impossible to know for sure). For more details, a comprehensive unit test, and an implicit version, check out my post here.