Cannot use normal array functions

时间:2015-07-28 22:41:53

标签: c# .net arrays

Why is it that i cannot use the normal array functions in C# like:

string[] k = {"Hello" , "There"};
k.RemoveAt(index); //Not possible

Code completion comes with suggestions like All<>, Any<>, Cast<> or Average<>, but no function to remove strings from the array. This happens with all kind of arrays. Is this because my build target is set to .NET 4.5.1?

2 个答案:

答案 0 :(得分:4)

You cannot "Add" or "Remove" items from an array, nor should you, as arrays are defined to be a fixed size. The functions you mention (All, Any) are there because Array<T> implements IEnumerable<T> and so you get access to the LINQ extensions.

While it does implement IList<T>, the methods will throw a NotSupportedException. In your case, to "remove" the string, just do:

k[index] = String.Empty; //Or null, whichever you prefer

答案 1 :(得分:1)

The length of an array is fixed when it's created and doesn't change, it represents a block of memory. Arrays do actually implement IList/IList<T>, but only partially - any method that tries to change the array is only available after casting and will throw an exception. Arrays are used internally in most collections.

If you need to add and remove arbitrarily and have fast acces by index you should use a List<T> which uses a resizing array internally.