Tag Archives: Extensions

Indexers as Extension Methods?

So I’ve had this nagging issue for a little while. It’s not necessarily a huge issue because I have a workaround, but that said, it still nags at me now and again. That issue is that I cannot create an indexer as an extension method. This isn’t possible for a number of reasons that make sense, but I thought I’d blog about it anyway and solicit thoughts on the idea.

First, let’s talk about what we can do. I can create an extension method for any existing class. Let’s say I have the following class already created:

public class SomeClass{
   public int SomeProperty { get; set; }
}

 

I can then extend a List of SomeClass pretty easily like this:

public static class Extensions{
   public static string SomeListExtensionProperty(this List<SomeClass> classes)   {
      //… provide implementation here …
   }
}

 

Notice that I’ve scoped my extension to only extend a generic List of SomeClass. For instance I can do this:

var sc = new List<SomeClass>();string s = sc.SomeListExtensionProperty();

 

but I cannot do this:

var soc = new List<SomeOtherClass>();
string s = soc.SomeListExtensionProperty();

 

So what would happen if I tried to extend the List of SomeClass with an indexer like this:

public static string this[int index](this List<SomeClass> classes){
 return classes[i].SomeProperty;
}

 

We wouldn’t get past compilation. First of all, the word “this” and “static” don’t mix or tend to make sense together in most cases. That is because “this” refers to an instance of a class while “static” refers to type itself. In general, mixing these two wouldn’t make sense. That said, we already mix these two keywords when we create extension methods. So that isn’t the only reason this wouldn’t work. The next reason is that the generic List class already provides an indexer. Since you can’t override existing members with extensions, you are left without the ability to create an indexer with an extension.

Our only recourse would be to provide extension methods that provide the same functionality as a method.

public static string GetSomeProperty(this List<SomeClass> classes, int index){
   return classes[index].SomeProperty;
}

 

We can then call something like this:

var sc = new List<SomeClass>();
string s = sc.GetSomeProperty(index);

 

This isn’t quite as abbreviated as an indexer and in fact doesn’t save me anything over what I would get with the out-of-the-box generic List indexer:

var sc = new List<SomeClass>();
string s = sc[index].SomeProperty;

 

That said, the “nagging issue” is more of a request for a solution looking for a problem. Obviously indexers are great shorthand that ‘can’ provide a ‘default property’ so-to-speak. However, it is very easy to get what you want without much work.