What are Indexers?
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
- A class can have only one Indexer
- In VB.net, default keyword is required to make it indexer
- Index can be accessed either by a numeric index or even string
How to Use (C#)?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSconsole
{
class NamesList
{
public int Length
{
get { return objList.Count; }
}
List<String> objList = new List<string>();
public string this[int index]
{
get { return objList[index]; }
set { objList.Add (value); }
}
}
public class TestIndexers
{
public static void
{
NamesList obj = new NamesList();
obj[0] = "UserA";
obj[1] = "UserB";
for(int i=0;i
{
Console.WriteLine(obj[i]);
}
Console.ReadKey();
}
}
}
How to Use (VB.net)?
Imports System.Collections.Generic
Public Class NamesList
Dim Names As New List(Of String)
Default Public Property LastName(ByVal index As Integer) As String
Get
Return Names(index)
End Get
Set(ByVal value As String)
Names.Add(value)
End Set
End Property
Public Property FirstName(ByVal index As Integer) As String
Get
Return Names(index)
End Get
Set(ByVal value As String)
Names.Add(value)
End Set
End Property
Public Shared Sub
Dim obj As New NamesList()
obj(0) = "User1"
Console.WriteLine(obj(0))
Console.Read()
End Sub
End Class