24

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 How to extend arrays in C#

Community
  • 1
  • 1
Jader Dias
  • 88,211
  • 155
  • 421
  • 625

3 Answers3

45
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
  • 6,403
  • 1
  • 27
  • 26
  • What does "this Array array" mean in the method. I think Array is an abstract class so what are you exactly doing here by writing "this Array array"? – VatsalSura Feb 07 '17 at 17:11
  • 3
    this Array array means that *this Array* is referring to the type that is to be extended. *this Array* could just as well be *this T*, where the method would be *public static void Extend(this T obj)*. The identifier merely gives the type a name, so it can be referenced in the extending method. – SimonC Apr 13 '17 at 08:40
  • @VatsalSura: "this Array array" refers to "extend any kind of array", as opposed to a more specific array kind, e.g. object[], object[][] or object[,] (or another type, as well as generics, instead of the example type "object"). I think this is what you were querying about. – Rob May 26 '23 at 03:58
41

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
  • 16,213
  • 5
  • 55
  • 85
  • 1
    +1 Your implementation is more type-safe than @maciejkow's. I wrote some array extension methods using a similar method some time ago. – Alex Essilfie Mar 01 '11 at 15:09
1

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
  • 88,211
  • 155
  • 421
  • 625
  • What does "this Array target" mean in the method. I think Array is an abstract class so what are you exactly doing here by writing "this Array target"? – VatsalSura Feb 07 '17 at 17:12