views:

621

answers:

3

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.

+1  A: 

It would be better to look into TypeConverter's.

leppie
A: 

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

Bender
+1  A: 

To directly answer your question ...

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)

... you can use something similar to this :

to.GetType().IsAssignableFrom(from.GetType());

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.

Alex Marshall
According to MSDN, IsAssignableFrom only considers equality, inheritance, interfaces, and generics, not cast operators.http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx
Bryan Matthews