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 …
Change the test to:
This is necessary because the property’s property-type is itself not an integer: it is a
System.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
foreachloop:(This will throw an exception if no such property exists.)
To retrieve the value of the property from an instance of the containing type:
This will of course fail if the ‘first’
Int32property 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. From
Type.GetProperties: