Thursday 18 February 2010

CSharp: Implement Indexer

Question:
How to implement an indexed property in c# ??
Do you have an example implementation of an Indexer in c#?




Answer:
The syntax is like this: public T this[string index]
So, if the name of a property is this[...], the compiler takes it for an indexer.

Here is an example
public class IndexList<T> : List<T> where T : INamedItem
{
    public T this[string index]
    {
        get{
            return this.FirstOrDefault<T>(o => o.Name == index);
        }
        set
        {
            if (string.IsNullOrEmpty(value.Name))
            {
                value.Name = index;
            }
            this.Add(value);
        }
    }
    public bool ContainsKey(string key)
    {
        return this.Any<T>(o => o.Name == key);
    }
    public void Add(string key, T value)
    {
        if (string.IsNullOrEmpty(value.Name))
        {
            value.Name = key;
        }
        this.Add(value);
    }
 
    private class ItemEqualityComparer<T> : IEqualityComparer<T>  where T: INamedItem
    {
        public bool Equals(T x, T y)
        {
            return x.Name.Equals(y.Name);
        }

        public int GetHashCode(T obj)
        {
            return obj.Name.GetHashCode();
        }
    }
}

public interface INamedItem
{
    string Name { get; set; }
}

No comments: