Coffeehouse Thread

6 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Using reflection, how to tell if a property is an indexer?

Back to Forum: Coffeehouse
  • User profile image
    BitFlipper

    Given a PropertyInfo of one of a class's properties, how can you tell if the property is an indexer? 

    For instance, if I have a class like this:

    class Foo
    {
        public string this[int index]
        {
            get { return index.ToString(); }
        }
    }
    


    So I need to be able to tell when the PropertyInfo is referring to an indexer. I can check whether the property's name is "Item", however that is unreliable since you can have a property called Item that isn't an indexer.

    Looking at the PropertyInfo in the debugger, I can see that within the RuntimePropertyInfo, there is a Signature property that has number of arguments. For a non-indexer, there will be 0 arguments. For an indexer, there will be one or more arguments. However RuntimePropertyInfo is an internal class so I cannot use any of its properties.

    BTW, PropertyInfo.IsSpecialName is false for an indexer.

    Any ideas?

  • User profile image
    Richard.Hein

    @BitFlipper: GetType().GetDefaultMembers()?

  • User profile image
    BitFlipper

    , Richard.Hein wrote

    @BitFlipper: GetType().GetDefaultMembers()?

    Yes, you are correct! Thanks Big Smile

  • User profile image
    Richard.Hein

    @BitFlipper: This will work:

     

     Foo f = new Foo();
    var indexers = from property in f.GetType().GetProperties()
    where property.GetIndexParameters().Any()
    select property;
    indexers.Dump();

     

  • User profile image
    Richard.Hein

    @BitFlipper: GetDefaultMembers will return all the indexers, but also any other member you've marked as default with the DefaultMemberAttribute.  However, GetIndexParameters should only return anything if it's an indexer, I think.  Combining the two would be safest if in doubt.

  • User profile image
    Richard.Hein

    @BitFlipper: Ah, I see "In C# it is an error to manually attribute a type with the DefaultMemberAttribute if the type also declares an indexer." in the link to the DefaultMemberAttribute documentation, so you'll only have a problem with that if there is no indexer, but there is another DefaultMember,

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.