using System;
using System.Collections.Generic;
namespace CSharpMagic.IndexerDemo
{
class CustomIndexers
{
public static void Main(string[] args)
{
NameCollection collection = new NameCollection();
collection["Name"] = "Xyz";
Console.WriteLine(collection["Name"]);
Console.ReadKey();
}
}
class NameCollection
{
private List<Pair> _pairs = new List<Pair>();
public string this[string key]
{
get
{
return _pairs != null && _pairs.Count > 0
?_pairs.Find(p => p.Key == key).Value
: string.Empty;
}
set
{
_pairs.Add(new Pair { Key = key, Value= value});
}
}
}
class Pair
{
public string Key { get; set; }
public string Value { get; set; }
}
}This code snippet is for custom indexer in c# like dictionary, where you access value by directly specifying Name or add an key value pair to collection by directly specifying the [name] = value.