UPDATE: Extension methods

Looks like I was way wrong in here and here.

I had thought that from the top of my head because I tried to use Array.IndexOf as an extension method and was surprised to see that it wasn’t an extension method.

It presented a good opportunity to play around with extension methods, so I wrote a class to extend the Array class:

public static class ArrayUtils


    public static int IndexOf<T>(this T[] array, T value)


        return System.Array.IndexOf(array, value);



    public static int IndexOf<T>(this T[] array, T value, int startIndex)


        return System.Array.IndexOf(array, value, startIndex);



    public static int IndexOf<T>(this T[] array, T value, int startIndex, int count)


        return System.Array.IndexOf(array, value, startIndex, count);



It was so easy that I thought: “Why dind’t they do it?”.

While I was trying to write a proof of concept around making such a change in a class (changing normal static methods into extension methods). It was as simple as adding a this keyword:

public class MyClass


    private int myField;


    public int MyProperty


        get { return myField; }

        set { myField = value; }



    public static bool IsNullOrEmpty(this MyClass value)


        if (value == null) return true;

        if (value.myField == 0) return true;

        return false;



The output of the compiler just chilled my enthusiasm:

MyCsClass.cs(18,47): error CS1106: Extension methods must be defined in a non generic static class

What is this all about? How had I missed it in here and here?

Here’s how I had missed it:



I should have tried this:


THIS is the most recent (I think) specification of C# 3.0 and it states that:

Extension methods are declared by specifying the keyword this as a modifier on the first parameter of the methods. Extension methods can only be declared in non-generic, non-nested static classes.

Now it’s all clear!