Insert At Element to an Array - CSharp System

CSharp examples for System:Array Element Add

Description

Insert At Element to an Array

Demo Code

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
using System.Diagnostics;
using System;//from   w w w. j  a v a2 s  . c  om

public class Main{
        internal static T[] InsertAt<T>(this T[] array, int position, T[] items)
        {
            T[] newArray = new T[array.Length + items.Length];
            if (position > 0)
            {
                Array.Copy(array, newArray, position);
            }

            if (position < array.Length)
            {
                Array.Copy(array, position, newArray, position + items.Length, array.Length - position);
            }

            items.CopyTo(newArray, position);
            return newArray;
        }
        internal static T[] InsertAt<T>(this T[] array, int position, T item)
        {
            T[] newArray = new T[array.Length + 1];
            if (position > 0)
            {
                Array.Copy(array, newArray, position);
            }

            if (position < array.Length)
            {
                Array.Copy(array, position, newArray, position + 1, array.Length - position);
            }

            newArray[position] = item;
            return newArray;
        }
        internal static T[] Copy<T>(this T[] array, int start, int length)
        {
            // It's ok for 'start' to equal 'array.Length'.  In that case you'll
            // just get an empty array back.
            Debug.Assert(start >= 0);
            Debug.Assert(start <= array.Length);

            if (start + length > array.Length)
            {
                length = array.Length - start;
            }

            T[] newArray = new T[length];
            Array.Copy(array, start, newArray, 0, length);
            return newArray;
        }
}

Related Tutorials