Search code examples
c#extension-methodsindexer

C# extend indexer?


Is it possible to use extension methods to extend an indexer? I want to be able to get cell's value from DataGridViewCell of given DataGridViewRow using header text like this:

object o = row["HeaderText"]; 

I have this code

public static class Ext
{
    public static object Cells(this DataGridViewRow r, string header)
    {
        foreach (DataGridViewCell c in r.Cells)
        {
            if (c.OwningColumn.HeaderText == header)
            {
                return c.Value;
            }
        }
        return null;
    }
}

and I want similar indexer. Thanks.


Solution

  • Indexers are actually properties, and extension properties do not exist in C#. So this can't be done the way you want.

    See this blog post for some background on the subject, and an explanation as to why that feature was considered, but ultimately omitted from C# 3.0.