views:

393

answers:

3

I'm used to add methods to external classes like IEnumerable. But can we extend Arrays in C#?

I am planning to add a method to arrays that converts it to a IEnumerable even if it is multidimensional.

Not related to http://stackoverflow.com/questions/628427/how-to-extend-arrays-in-c

+3  A: 
static class Extension
{
    public static string Extend(this Array array)
    {
        return "Yes, you can";
    }
}

class Program
{

    static void Main(string[] args)
    {
        int[,,,] multiDimArray = new int[10,10,10,10];
        Console.WriteLine(multiDimArray.Extend());
    }
}
maciejkow
A: 

I did it!

public static class ArrayExtensions
{
    public static IEnumerable<T> ToEnumerable<T>(this Array target)
    {
        foreach (var item in target)
            yield return (T)item;
    }
}
Jader Dias
A: 

Yes. Either through extending the Array class as already shown, or by extending a specific kind of array or even a generic array:

public static void Extension(this string[] array)
{
  // Do stuff
}

// or:

public static void Extension<T>(this T[] array)
{
  // Do stuff
}

The last one is not exactly equivalent to extending Array, as it wouldn't work for a multi-dimensional array, so it's a little more constrained, which could be useful, I suppose.

JulianR