Chapter107:Indexer

No Comments

Section107.1:Asimpleindexer

classFoo

{

privatestring[]cities=new[]{“Paris”,”London”,”Berlin”};

publicstringthis[intindex]

{

get{

returncities[index];

}

set{

cities[index]=value;

}

}

}

Usage:

varfoo=newFoo();

//accessavalue

stringberlin=foo[2];

//assignavalue

foo[0]=”Rome”;

ViewDemo

Section107.2:Overloadingtheindexertocreatea SparseArray

Byoverloadingtheindexeryoucancreateaclassthatlooksandfeelslikeanarraybutisn’t.ItwillhaveO(1)getand set methods, can access an element at index 100, and yet still have the size of the elements inside of it. The SparseArray class

classSparseArray

{

Dictionary<int,string>array=newDictionary<int,string>();

publicstringthis[inti]

{

get

{

if(!array.ContainsKey(i))

{

returnnull;

}

returnarray[i];

}

set

{

if(!array.ContainsKey(i))

array.Add(i,value);

}

}

}

Section107.3:Indexerwith2argumentsandinterface

interfaceITable{

//anindexercanbedeclaredinaninterface

objectthis[intx,inty]{get;set;}

}

classDataTable:ITable

{

privateobject[,]cells=newobject[10,10];

///<summary>

///implementationoftheindexerdeclaredintheinterface

///</summary>

///<paramname=”x”>X-Index</param>

///<paramname=”y”>Y-Index</param>

///<returns>Contentofthiscell</returns>

publicobjectthis[intx,inty]

{

get

{

returncells[x,y];

}

set

{

cells[x,y]=value;

}

}

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Leave a Comment