0

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
  • Can you explain in further details please? Commented Jul 28, 2015 at 22:46
  • I could do that before. Commented Jul 28, 2015 at 22:47

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ohh... I must have mixed it with the List<> object :3
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.

1 Comment

+1 for noting that it does implement IList, through the methods will throw. Thanks for correcting me on that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.