1

What is the easiest way to determine if a reflected property can be assigned a given value ?

The method signature of what I need is :

public static bool IsAssignable(PropertyInfo property, object value)
{        
    throw new NotImplementedException();
}

This method should work for value type and reference type and weither value is null or not.

Thanks for you help guys.

Manitra.

3 Answers 3

4

You are probably looking for Type.IsAssignableFrom

1
  • Ok, Thanks. But if the value is null and I can't can't call GetType() on it ? Mar 8, 2011 at 14:05
3

You can't determine the type of null which is passed as object. You only can say if the property is able to take null at all.

You could take the compile-time type for that reason:

public static bool IsAssignable<T>(PropertyInfo property, T value)
{        
    if (value != null)
    {
        return property.PropertyType.IsAssignableFrom(value.GetType());
    }
    return property.PropertyType.IsAssignableFrom(typeof(T));
}
1
  • Thanks for this answer, it's correct in a strongly typed use case (upvoted). In my case, I really have an object as value so I can't use typeof(T). But, actually, I found a similar question which deals with a null value so it's ok. Mar 8, 2011 at 14:40
2

Thanks to Stefan's and John responses, and the "Determine if a reflected property can be assigned null" question, here is the code I'll use :

public static bool IsAssignable(PropertyInfo property, object value)
{
    if (value == null && property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) == null)
        return false;
    if (value != null && !property.PropertyType.IsAssignableFrom(value.GetType()))
        return false;
    return true;
}

This works for all cases and in a pure loosely typed fashion.

Manitra.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.