User Tools

Site Tools


indexers_indexed_property

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
indexers_indexed_property [2018/09/06 19:25] – created wolfgangriedmannindexers_indexed_property [2018/09/11 08:37] (current) wolfgangriedmann
Line 1: Line 1:
 ====== Indexers and indexed properties ====== ====== 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:
 +<code visualfoxpro>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</code>
 +This class can be used like this:
 +<code visualfoxpro>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</code>
 +
 +Classes with indexed properties can also be used like classes with dynamic arrays. Please see this sample:
 +<code visualfoxpro>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</code>
 +To be used like this:
 +<code visualfoxpro>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"] )</code>
 +
 +Please see also this Microsoft article: [[https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/|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 Please see https://www.xsharp.info/forum/public-product/839-indexer-syntax
  
indexers_indexed_property.1536261925.txt.gz · Last modified: 2018/09/06 19:25 by wolfgangriedmann