tags:

views:

35

answers:

2

Im saving an object model out to XML but when i load it back in I get exceptions when trying to use PropertyInfo.SetValue() because the property doesn't have a setter just a getter.

I want to either not save out the properties that only have getters or figure out on load whether its valid for me to try and set a value or not.

Anybody know how to do this

Cheers

+3  A: 

You can use PropertyInfo.GetSetMethod - this will return null if either the property is read-only or the setter is non-public.

if (property.GetSetMethod() != null)
{
    // Yup, you can write to it.
}

If you can cope with a non-public setter, you can use:

if (property.GetSetMethod(true) != null)
{
    // Yup, there's a setter - but it may be private
}
Jon Skeet
you know an unfathomable amount of stuff. thanks
DrLazer
A: 

Use PropertyInfo.CanWrite property.

Romain Verdier
FYI, this will return true even for non-public setters.
Dan Bryant