Question Trouble deleting/removing element in an array

DCC

New member
Joined
Aug 9, 2019
Messages
2
Programming Experience
Beginner
What I've done - made an array and put values in each element

int x;
int[] d = new int[6];

for(x=0;x<6;x++)
{
d[x] = x;
}

d[0]=0 d[1]=1 d[2]=2 d[3]=3 d[4]=4

What I want to do
get rid of element 3 so that
d[0]=0 d[1]=1 d[2]=3 d[3]=4


What I tried and what happened
d.delete
d.remove
neither delete or remove were available options

Delete.
Remove.
neither delete or remove were available options

Am I supposed to include something that I don't know about?
Are there other keywords I am supposed to use
 
Firstly, please post your code snippets as formatted code. There is an option on the editor toolbar to do so, which provides syntax highlighting and, most importantly, maintains indenting. It makes it far easier for us to read the code.

As for the issue, it's impossible. Arrays are fixed-size. If you create an array with six elements then that array always has six elements. You can't delete an element and you can't even move an element. All you can do is change the value of an element. Think of an array as a grouping of variables. An array with six elements is basically a group of six variables. Just like any other variables, you could set each element to another value or assign the value from one to another, but the elements themselves are always where they are.

If you want an array-like data structure that allows you to add and remove items as desired then you want a collection and, more specifically, a List<T>. T can be any type you like, e.g. in your case you would create a List<int>. The list is empty by default, like an array with no elements, and you can call the Add method to add an item to the end of the list or the Insert method to insert an item at a specific index. You get and set items in the list by index, just as you would with an array. There are also Remove and RemoveAt methods to remove specific items and items at a specific index.
 
Back
Top Bottom