How to remove an element from a regular array in C#?

How to remove an element from an regular array in C#?

Well, you can’t really change a regular array or remove an item from it. You have to create a new array that is a copy of the current array without the one value you want.

Here is a quick static class I created that will copy your array, leaving out the one item you don’t want.

namespace ArrayItemDeleter
{
    static class ArrayItemDeleter
    {
        public static void RemoteArrayItem<T>(ref T[] inArray, int inIndex)
        {
            T[] newArray = new T[inArray.Length - 1];
            for (int i = 0, j = 0; i < newArray.Length; i++, j++)
            {
                if (i == inIndex)
                {
                    j++;
                }
                newArray[i] = inArray[j];
            }
            inArray = newArray;
        }
    }
}

Here is how you would use it in your program.

using System;

namespace ArrayItemDeleter
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] str = {"1","2","3","4","5"};
            ArrayItemDeleter.RemoteArrayItem(ref str, 2);
        }
    }
}

Now, if you really want to add and remove items a lot, you should use a System.Collections.Generic.List object;

One Comment

  1. simi says:

    hi,

    First of all. Thanks very much for your useful post.

    I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

    Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

    There is a good C# resource site, Have alook

    http://csharptalk.com

    simi

Leave a Reply

Powered by sweetCaptcha