Search code examples
c#propertiesindexed-properties

Non-integer indexed Indexer properties in C#


I want to have an indexed property in C#:

public Boolean IsSelected[Guid personGuid]
{
   get {
      Person person = GetPersonByGuid(personGuid);
      return person.IsSelected;
   }
   set {
      Person person = GetPersonByGuid(personGuid);
      person.IsSelected = value;
   }
}
public Boolean IsApproved[Guid personGuid]
{
   get {
      Person person = GetPersonByGuid(personGuid);
      return person.IsApproved;
   }
   set {
      Person person = GetPersonByGuid(personGuid);
      person.IsApproved= value;
   }
}

Visual Studio complains on the non-integer indexer syntax:

i know .NET supports non-Integer indexors.


In another language i would write:

private
   function GetIsSelected(ApproverGUID: TGUID): Boolean;
   procedure SetIsSelected(ApproverGUID: TGUID; Value: Boolean);
   function GetIsApproved(ApproverGUID: TGUID): Boolean;
   procedure SetIsApproved(ApproverGUID: TGUID; Value: Boolean);
public
   property IsSelected[ApproverGuid: TGUID]:Boolean read GetIsSelected write SetIsSelected;
   property IsApproved[ApproverGuid: TGUID]:Boolean read GetIsApproved write SetIsApproved;
end;

Solution

  • Your syntax is incorrect:

    public Boolean this[Guid personGuid]
    {
       get {
          Person person = GetPersonByGuid(personGuid);
          return person.IsSelected;
       }
       set {
          Person person = GetPersonByGuid(personGuid);
          person.IsSelected = value;
       }
    }
    

    Indexers are declared using the this keyword - you can't use your own name.

    From Using Indexers (C# Programming Guide):

    To declare an indexer on a class or struct, use the this keyword


    Additionally, it is only possible to have one indexer that accepts a type - this is a limitation of the indexer syntax of C# (might be an IL limitation, not sure).