Is it possible to extend arrays in C#?

23,501

Solution 1

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());
    }
}

Solution 2

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.

Solution 3

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;
    }
}
Share:
23,501
Jader Dias
Author by

Jader Dias

Perl, Javascript, C#, Go, Matlab and Python Developer

Updated on March 28, 2022

Comments

  • Jader Dias
    Jader Dias about 2 years

    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#

  • Alex Essilfie
    Alex Essilfie about 13 years
    +1 Your implementation is more type-safe than @maciejkow's. I wrote some array extension methods using a similar method some time ago.
  • VatsalSura
    VatsalSura over 7 years
    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
    VatsalSura over 7 years
    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"?
  • SimonC
    SimonC about 7 years
    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<T>(this T obj). The identifier merely gives the type a name, so it can be referenced in the extending method.