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.

[sourcecode language=”csharp”]
namespace ArrayItemDeleter
static class ArrayItemDeleter
public static void RemoteArrayItem(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; } } } [/sourcecode]Here is how you would use it in your program.[sourcecode language="csharp"] using System;namespace ArrayItemDeleter { class Program { static void Main(string[] args) { string[] str = {"1","2","3","4","5"}; ArrayItemDeleter.RemoteArrayItem(ref str, 2); } } } [/sourcecode]Now, if you really want to add and remove items a lot, you should use a System.Collections.Generic.List object;

Leave a Reply

How to post code in comments?