tags:

views:

88

answers:

3

i have this code to loop through an object and get all of its properties through reflection

  foreach (var propertyInfo in typeof(TBase).GetProperties(BindingFlags.Public | BindingFlags.Instance))
  {
        var oldValue = propertyInfo.GetValue(oldVersion, null);
  }

how can i do a check to only look at properties that have a "Set" on them (i want to ignore read only values - just get)

+3  A: 

propertyInfo.GetSetMethod() != null

Kirk Woll
+8  A: 

PropertyInfo.CanWrite (documentation)

or

PropertyInfo.GetSetMethod (documentation)

STO
This will definitely work, but you'll have to do an extra check for each property. By setting BindingFlags.SetProperty you will only ever retrieve properties that contain setters.
Wallace Breza
I would recommend using the PropertyInfo.GetSetMethod and checking if it is null; the PropertyInfo.CanWrite method will return true if there is a private, protected, or internal set on the property. It will only return false if there is actually no setter on the property.
Dr. Wily's Apprentice
+7  A: 

Just add BindingFlags.SetProperty to your flags before getting your propreties.

foreach (var propertyInfo in typeof(TBase).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
{
    var oldValue = propertyInfo.GetValue(oldVersion, null);
}
Wallace Breza
This looks like the cleanest method to me.
mpenrow
I don't believe that you can use BindingFlags.SetProperty to query for properties with setters. That flag can be used when you want to perform an action that involves actually setting a property, such as with the Type.InvokeMember method.
Dr. Wily's Apprentice