views:

42

answers:

1

Hi folks,

I'm trying to find the first property of a class that is an Integer .. and get it's value.

So i've got the following code .. which always returns false:

foreach(var property in type.GetProperties(BindingFlags.Public |
    BindingFlags.Instance))
{
    var someType = property.PropertyType is int; // Always false.
}

Why is this / what did I do wrong. This should be really simple :(

/me is having a bad day ...

+4  A: 

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.Typeobject 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 GetPropertiesmethod 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.

Ani
You can use == instead of .Equals here, as Type objects are unique for a particular type. Not a criticism - your code will work, of course - I just find == easier to read.
Jon Skeet
Pure.Krome
+1 exactly, what's in PropertyType is not an instance of int, is an instance of System.Type.
eglasius
@Jon Skeet: Thank you, sir. You're right about the readability, updated.
Ani