AFusco
AFusco

Reputation: 474

c# check at runtime if two objects are comparable

I'm trying to understand the mechanisms of reflection. I want to compare an object's property with a given value. Now, instead of executing the comparison and catch an exception, I want to be able to know (of course at runtime) if the two objects are comparable.

Something like:

public bool IsComparableWithProperty(string propertyName, object value)
{
    return typeof(MyType).GetProperty(propertyName).PropertyType is IComparable<value.GetType()>        
}

Of course I know that this is not valid as generics must be known at compile-time. I was wondering if this kind of behaviour would be possible to implement in C#.

Thanks

Upvotes: 1

Views: 422

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249486

You can use MakeGenericType to instantiate the generic interface definition with the value runtime type and use IsAssignableFrom to check compatibility.

public bool IsComparableWithProperty(string propertyName, object value)
{
    return typeof(IComparable<>).MakeGenericType(value.GetType()).IsAssignableFrom(typeof(MyType).GetProperty(propertyName).PropertyType);
}

Upvotes: 3

Related Questions