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:

http://search.msdn.microsoft.com/search/Default.aspx?brand=msdn&query=%22non-nested%22+%22non-generic%22+%22static+class%22+%22extension+methods%22

http://search.live.com/results.aspx?q=%22non-nested%22+%22non-generic%22+%22static+class%22+%22extension+methods%22

I should have tried this:

http://www.google.com/custom?client=pub-3578125481836759&channel=1972798655&cof=S%3Ahttp%3A%2F%2Fsearchdotnet.com%2Fdefault.aspx%3BCX%3ADotNet%2520Developers%2520Search%2520Engine%3BL%3Ahttp%3A%2F%2Fwww.searchdotnet.com%2Fimages%2Fsearchnet.jpg%3BLH%3A36%3BLP%3A1%3B&q=%22non-nested%22+%22non-generic%22+%22static+class%22+%22extension+methods%22

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!