Search code examples
c#reflectioncastingoperator-keywordpropertyinfo

Possible to test a cast to PropertyInfo.PropertyType when object implements implicit operator?


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);
}

Solution

  • 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
    }