Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropertyInfo : is the property an indexer?

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.

like image 533
JYL Avatar asked Jan 20 '11 10:01

JYL


People also ask

What is Property and indexer?

Properties are identified by the names. While indexers are identified by the signatures. 3. Properties can be declared as a static or an instance member. Indexers are always declared as instance member, never as static member.

What is PropertyInfo?

< Previous Next > The PropertyInfo class discovers the attributes of a property and provides access to property metadata. The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance.

What is indexer C sharp?

Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.


2 Answers

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

like image 142
Jon Skeet Avatar answered Sep 22 '22 15:09

Jon Skeet


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.

like image 23
glopes Avatar answered Sep 23 '22 15:09

glopes