Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell Reflectively if an Attribute has a public Setter

Tags:

c#

reflection

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

like image 408
DrLazer Avatar asked May 11 '10 13:05

DrLazer


1 Answers

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
}
like image 164
Jon Skeet Avatar answered Oct 11 '22 21:10

Jon Skeet