Append to array - CSharp System

CSharp examples for System:Array Element Add

Description

Append to array

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;// w ww.j a v  a 2 s  .c  o  m

public class Main{
        public static T[] Append<T>(this T[] a, T b) {
            if(a != null && b != null) {
                try {
                    int length = a.Length + 1;
                    T[] merged = new T[length];
                    int i = 0;
                    foreach(T listItem in a) {
                        merged[i++] = listItem;
                    }
                    merged[i++] = b;

                    Debug.Assert(i == length);

                    return merged;
                } catch(Exception e) {
                    Log.error("Array helper merge failed", e);
                }
            } else if(a != null) {
                return a;
            } else if(b != null) {
                return new[] { b };
            }

            Debug.Fail();
            return null;
        }
        public static T[] Append<T>(this T[] a, T[] b) {
            if(a != null && b != null) {
                try {
                    int length = a.Length + b.Length;
                    T[] merged = new T[length];
                    int i = 0;
                    foreach(T listItem in a) {
                        merged[i++] = listItem;
                    }
                    foreach(T listItem in b) {
                        merged[i++] = listItem;
                    }

                    Debug.Assert(i == length);

                    return merged;
                } catch(Exception e) {
                    Log.error("Array helper merge failed", e);
                }
            } else if(a != null) {
                return a;
            } else if(b != null) {
                return b;
            }

            Debug.Fail();
            return null;
        }
}

Related Tutorials