According to the official docs, arrays in C# implement the following interfaces:
IList
IEnumerable
In the docs for IList
, I see that one of the listed methods is a Remove
method which does the following:
Removes the first occurrence of a specific object from the IList.
I wanted to use this method, so I wrote the following minimal program:
class RemoveAllOccurences {
static void Main()
{
int[] a = {1, 0, 0, 3};
a.Remove(0);
}
}
I then compiled with the following:
csc test.cs -out:test.exe
Running the executable threw the following error:
remove_issue.cs(7,11): error CS1061: 'int[]' does not contain a definition for 'Remove' and no accessible extension method 'Remove' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)
I'm not sure why Remove
is not recognized, since as I mentioned before it is part of the IList
interface shown in the docs.
What am I doing wrong here?
CodePudding user response:
Arrays implement IList.Remove
via explicit interface implementation, which means you can only access it via a reference with a compile-time type of the interface type. So for example:
int[] a = {1, 0, 0, 3};
IList list = a;
list.Remove(0);
That compiles with no problem. However, it will then throw an exception (NotSupportedException
) at execution time because arrays are of fixed size - Remove
and Add
operations don't make sense on them. That's why those methods are implemented with explicit interface implementation, to avoid you using them inappropriately...