Articles → .NET → Indexers in C#
Indexers in C#
Introduction
Syntax
<modifier> <return type> this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
Creation of XML file
<root>
<subject value = ".Net"></subject>
<subject value = ".Net Web Service"></subject>
<subject value = "ADO.NET"></subject>
<subject value = "IBM Lotus Notes"></subject>
<subject value = "JavaScript"></subject>
<subject value = "Silverlight"></subject>
<subject value = "Software Testing"></subject>
<subject value = "SQL Server"></subject>
<subject value = "WPF"></subject>
</root>
Creating a class to implement indexer
class Subject
{
private Dictionary<string,string> _subjectDictionary = new Dictionary<string,string>();
/// <summary>
/// Indexer
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public string this[int index]
{
get
{
string key = _subjectDictionary.Keys.Where((n, i) => i == index).FirstOrDefault();
return string.Format("{0}",_subjectDictionary[key]);
}
}
/// <summary>
/// Get List of subjects
/// </summary>
private void GetListOfSubjects()
{
DataSet ds = new DataSet();
ds.ReadXml("subject.xml");
for (int i = 0; i < ds.Tables[0].Rows.Count - 1; i++)
{
_subjectDictionary.Add(i.ToString(), ds.Tables[0].Rows[i]["value"].ToString());
}
}
/// <summary>
/// Constructor
/// </summary>
public Subject()
{
if (_subjectDictionary.Count == 0)
{
GetListOfSubjects();
}
}
/// <summary>
/// Subject Count to save from
/// index out of range
/// </summary>
public int SubjectCount
{
get
{
return _subjectDictionary.Count;
}
}
}
Code explanation
private Dictionary<string,string> _subjectDictionary = new Dictionary<string,string>();
public string this[int index]
{
get
{
string key = _subjectDictionary.Keys.Where((n, i) => i == index).FirstOrDefault();
return string.Format("{0}",_subjectDictionary[key]);
}
}
Reading the xml file
Subject oSubject = new Subject();
StringBuilder sbMenu = new StringBuilder(string.Empty);
sbMenu.Append("<ul id = \"MenuLeft\">");
for (int i = 0; i < oSubject.SubjectCount; i++)
{
sbMenu.Append("<li>");
sbMenu.Append(oSubject[i].ToString());
sbMenu.Append("</li>");
}
sbMenu.Append("</ul>");
divLeftMenu.InnerHtml = sbMenu.ToString();
Conclusion