Change the test to:
var firstInt32Property = property.PropertyType == typeof(int);
This is necessary because the property's property-type is itself not an integer: it is aSystem.Type
object that (loosely) represents what type the property-getter returns / property-setter accepts. On the other hand, invoking the property getter on an instance of the containing-type will produce an actual integer.
Here's a way to use LINQ instead of the foreach
loop:
var firstInt32Property = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.First(p => p.PropertyType == typeof(int));
(This will throw an exception if no such property exists.)
To retrieve the value of the property from an instance of the containing type:
int value = (int)firstInt32Property.GetValue(myObj, null);
This will of course fail if the 'first' Int32
property happens to be an indexer or indeed if it simply doesn't have a getter. You could filter such properties out on the original query if such scenarios are likely.
Also note that this code is of limited use because the idea of 'the first property of a class that is an integer' is a little bit suspect. FromType.GetProperties
:
The GetProperties
method does not
return properties in a particular
order, such as alphabetical or
declaration order. Your code must not
depend on the order in which
properties are returned, because that
order varies.