0

I have an object of a certain type (SpecialImage) which implements an implicit operator to another type (Image).

SpecialImage does not derive from Image. However the following is possible through the operator:

var someImage = new Image();
(SpecialImage)someImage;

I have an object with properties which I'm looping through by reflection and an Image object:

Is it possible to check if the object is castable to info.PropertyType before trying to set the value?

var someImage = new Image();

foreach(PropertyInfo info in someOjbect.GetType().GetProperties()) {
    //info.PropertyType == typeof(SomeImage);

    //Is it possible to check if the object is castable to 
    //info.PropertyType before trying to set the value?
    info.SetValue(someObject, someImage, null);
}
Ropstah
  • 17,538
  • 24
  • 120
  • 194

1 Answers1

1

You could try something like this

If we have these classes

class T1
{
}

class T2
{
    public static implicit operator T1(T2 item) { return new T1(); }
}

The we could use

if(typeof(T2).GetMethods().Where (
    t => t.IsStatic && t.IsSpecialName && 
         t.ReturnType == typeof(T1) && t.Name=="op_Implicit").Any())
{
    // do stuff
}
Phil
  • 42,255
  • 9
  • 100
  • 100
  • I found this and indeed this works. Is there no nicer way __without__ having to change the class and for instance convert IConvertible? – Ropstah Apr 06 '12 at 11:58
  • 1
    Not that I know of. You could wrap that code in a helper method to tidy it away. See http://stackoverflow.com/questions/2075471/implicit-version-of-isassignablefrom and http://stackoverflow.com/questions/2224266/how-to-tell-if-type-a-is-implicitly-convertible-to-type-b for more info. – Phil Apr 06 '12 at 12:27