October 15, 2009

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

Filed under: C# (C-Sharp) — J. Abram barneck @ 7:27 am

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)
                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;

1 Comment »

  1. 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



    Comment by simi — December 29, 2009 @ 11:46 pm | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: