uzay95
uzay95

Reputation: 16622

Creating array from existing one

This is the code:

class Program
{
    void Add2Array(object arr, object item)
    {
        if (arr.GetType() == typeof(string[]))
        {
            int iLen = (arr as Array).Length;
            var c = Array.CreateInstance(typeof (String), 3);
            Array v = Array.CreateInstance((arr as Array).GetValue(0).GetType(), iLen+1); // this works but when if arr is empty it wont work
            Array.Copy(ar, v, iLen);
            v.SetValue(item, iLen);
        }
    }
    public string[] sarr = new string[1];

    static void Main(string[] args)
    {
        Program p = new Program();
        p.sarr[0] = "String Item";
        p.Add2Array(p.sarr, "New string item");
    }
}

I want to create a method which can take every type of arrays and put new item into them. Above code is my solution (if you know better please share) and if arr parameter hasn't any item, it won't work properly. Because if I use this Array.CreateInstance(arr.GetType(),3) it will create new array like this v.GetType() => string[2][] because arr is string array and if i create with same type it is returning two dimensonal array.

How can I extend an array(given as a parameter) and put new item into it ?

Upvotes: 0

Views: 2591

Answers (2)

Sergei B.
Sergei B.

Reputation: 3227

Array cannot be extended. The only thing you could do is to copy data to a new array which is bigger than original one and append data.

BTW, why not to use List<>?

using System;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            int[] x = new int[]{2,3,5};
            int[] y = new ArrayExpander().AddItem(x, 0);

            foreach (var i in y)
            {
                Console.Write(i);
            }
        }
    }

    class ArrayExpander
    {
        public T[] AddItem<T>(T[] source, T item)
        {
            var destination = new T[source.Length + 1];
            Array.Copy(source, destination, source.Length);
            destination[source.Length] = item;
            return destination;
        }
    }
}

Upvotes: 3

Jason Meckley
Jason Meckley

Reputation: 7591

T[] Add2Array<T>(T[] arr, T item)
{
   return arr.Concat(new[]{item}).ToArray();
}

Upvotes: 5

Related Questions