I have a class with a custom indexer like so
public string this[VehicleProperty property]
{
// Code
}
How can I identify the custom index
If there is only one indexer, you can use this:
var indexer = typeof(MyClass).GetProperties().First(x => x.GetIndexParameters().Length > 0));
If there are multiple indexers, you can select the overload you want by supplying the arguments like this:
var args = new[] { typeof(int) };
var indexer = typeof(MyClass).GetProperties().First(x => x.GetIndexParameters().Select(y => y.ParameterType).SequenceEqual(args));
You can create a helper extension like this:
//Usage
var indexer = typeof(MyClass).GetIndexer(typeof(VehicleProperty));
//Class
public static class TypeExtensions
{
public static PropertyInfo GetIndexer(this Type type, params Type[] arguments) => type.GetProperties().First(x => x.GetIndexParameters().Select(y => y.ParameterType).SequenceEqual(arguments));
}
To get a known indexer you can use:
var prop = typeof(MyClass).GetProperty("Item", new object[]{typeof(VehicleProperty)});
var value = prop.GetValue(classInstance, new object[]{ theVehicle });
or you can get the getter method of the indexer:
var getterMethod = typeof(MyClass).GetMethod("get_Item", new object[]{typeof(VehicleProperty)});
var value = getterMethod.Invoke(classInstance, new object[]{ theVehicle });
if the class has only one indexer, you can omit the type:
var prop = typeof(MyClass).GetProperty("Item", , BindingFlags.Public | BindingFlags.Instance);
I've added this answer for the ones who google search led them here.
Look for the DefaultMemberAttribute defined at type level.
(This used to be IndexerNameAttribute, but they seem to have dropped it)
static void Main(string[] args) {
foreach (System.Reflection.PropertyInfo propertyInfo in typeof(System.Collections.ArrayList).GetProperties()) {
System.Reflection.ParameterInfo[] parameterInfos = propertyInfo.GetIndexParameters();
// then is indexer property
if (parameterInfos.Length > 0) {
System.Console.WriteLine(propertyInfo.Name);
}
}
System.Console.ReadKey();
}
You can also look for index parameters, using the the PropertyInfo.GetIndexParameters method, if it returns more than 0 items, it's an indexed property:
foreach (PropertyInfo pi in typeof(MyClass).GetProperties())
{
if (pi.GetIndexParameters().Length > 0)
{
// Indexed property...
}
}