2

I have an indexer method inside a class that allows me to do this:

var foo = Class["bar"];
Class["bar"] = foo;

Here it is:

public object this[string propertyName]
{
    get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
    set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}

I want to get an array of PropertyInfo[] and loop through it to get the values of the properties. But this extension method (type System.Object) is making its way in the array and I don't know how to exclude it.

I could exclude it inside my loop. But it could be problematic if my class does contain an "Item" property. Any ideas?

PropertyInfo[] properties = typeof(Class).GetProperties();
foreach(var prop in properties)
    if(prop.name == "Item")
        continue;

enter image description here

Kyle
  • 5,407
  • 6
  • 32
  • 47

2 Answers2

3

You can determine if a property is an indexer by using the PropertyInfo.GetIndexParameters() method:

PropertyInfo[] properties = typeof(Class).GetProperties();
foreach(var prop in properties)
    if(prop.GetIndexParameters().Length > 0)  // it is an indexer
        continue;

If the method returns a non-empty array then it is an indexer. That way you don't have to rely on the default name of Item that the compiler generates unless overridden by an attribute.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

You can check the number of IndexParameters and, if more than 0, exclude it.

foreach(var prop in typeof(Class).GetProperties()
    .Where (x => x.GetIndexParameters().Length <= 0))
{        
    if(prop.name == "Item")
        continue;
}
David L
  • 32,885
  • 8
  • 62
  • 93