Indexers and indexed properties

Indexers are a new concept for xBase developers. They permit to access the properties of an object like an array. Please see this sample class:

class IndexerTest
protect oValues	as List<string>
 
constructor()
 
oValues := List<string>{}
 
return
 
property self[ nIndex as int ] as string
  get
    if oValues:Count >= nIndex
      return oValues[nIndex-1]
    else
      return ""
    endif
  end get
  set	
    while oValues:Count < nIndex
      oValues:Add( "" )
    end
    oValues[nIndex-1]		:= value
  end set
end property
 
end class

This class can be used like this:

function Start( ) as void
local oTest as IndexerTest
local nI as int
 
oTest := IndexerTest{}
oTest[1] := "Chris"
oTest[2] := "Fabrice"
oTest[3] := "Nikos"
oTest[4]:= "Robert"
 
for nI := 1 upto 5
  Console.WriteLine( i"Element {nI}:" + oTest[nI] )
next
 
return

Classes with indexed properties can also be used like classes with dynamic arrays. Please see this sample:

class IndexedProperty
protect _oValues as Dictionary<string,string>
 
constructor()
  _oValues		:= Dictionary<string,string>{} 
return
 
property self[cName as string] as string
  get	
    local cValue as string
    if _oValues:TryGetValue( cName, OUT cValue ) == false
      cValue := "< not assigned >"
    endif
    return cValue
  end get
  set             
    if _oValues:ContainsKey( cName )
      _oValues[cName]		:= value
    else
      _oValues:Add( cName, value )
    endif
end set
end property	
 
end class

To be used like this:

oObject := IndexedProperty{}
oObject["MyProp"] := "Hello X#"   
oObject["Prop2"] := "Hello again"
System.Console.WriteLine( "MyProp:" + oObject["MyProp"] )
System.Console.WriteLine( "Prop2:" + oObject["Prop2"] )
System.Console.WriteLine( "Prop3:" + oObject["Prop3"] )

Please see also this Microsoft article: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/

And there is also a forum thread about this: Please see https://www.xsharp.info/forum/public-product/839-indexer-syntax