Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend arrays in C#?

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#

like image 901
Jader Dias Avatar asked Jul 25 '09 21:07

Jader Dias


People also ask

Can you expand an array in C?

You can't resize an array in C, their size is set at compile time. You can have a dynamically-sized array-like memory region, but you have to use memory allocation.

Is it possible to increase the size of an array?

Arrays can either hold primitive values or object values. An ArrayList can only hold object values. You must decide the size of the array when it is constructed. You can't change the size of the array after it's constructed.

Can we change size of array at runtime in C?

No. In an array declaration, the size must be known at compile time. You can�t specify a size that�s known only at runtime.

Can we increase array size during runtime?

Size of an array Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array. Still if you try to assign value to the element of the array beyond its size a run time exception will be generated.


3 Answers

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());
    }
}
like image 105
maciejkow Avatar answered Nov 03 '22 17:11

maciejkow


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.

like image 30
JulianR Avatar answered Nov 03 '22 17:11

JulianR


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;
    }
}
like image 39
Jader Dias Avatar answered Nov 03 '22 18:11

Jader Dias