47

I have the following code :

PropertyInfo[] originalProperties = myType.GetProperties();

I want to exclude from originalProperties all the indexers (myVar["key"] appears as property named "Item").

What is the proper way ?

Exclude all properties where propInfo.Name == "Item" is not an option.

JYL
  • 8,228
  • 5
  • 39
  • 63

2 Answers2

76

Call PropertyInfo.GetIndexParameters - if the returned array is empty, it's not an indexer.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Hmm... This may work but it is rather heavy handed. There has to be a "lighter" way of getting that info. – Eniola May 20 '18 at 06:24
  • @Eniola: I don't see why there "has" to be a lighter (by which I assume you mean more efficient) way. If you're doing this a lot and you care about performance, I suggest you cache the results. – Jon Skeet May 20 '18 at 14:03
  • Yeah, that's the current state of the union. So we have to cache. How about if the .NET runtime we adjusted to explicitly add that flag to the metadata so there isn't as much of a hit. Because my scenario involves rewriting objects returned in a WebApi to include the href value; that involves inspecting a lot of properties on many Types. So what do you cache and what do you let go considering memory use can quickly grow? – Eniola May 23 '18 at 13:04
  • @Eniola: This feels like a somewhat different question to the one asked 7 years ago. You may want to ask a new, specific question. – Jon Skeet May 23 '18 at 13:39
  • @Eniola: the results appear to be already cached, as of the latest [reference source](https://referencesource.microsoft.com/#mscorlib/system/reflection/propertyinfo.cs,1f644b9f39491b44) – glopes Jan 15 '19 at 13:00
2

Another option is to use:

myType.GetProperties().Except(myType.GetDefaultMembers().OfType<PropertyInfo>());

GetDefaultMembers will return all the compiler generated indexers in C#. This has the advantage of not needing to reflect on each individual property in order to find out which ones are indexers.

This might not be a general solution for all allowed .NET framework languages, but I am currently not aware of any counter-examples.

glopes
  • 4,038
  • 3
  • 26
  • 29