3D-kreativ
3D-kreativ

Reputation: 9309

Need to remove object from list before insert new object?

I'm learning C# and I'm doing a task where I'm using a list of objects. I thought if I inserted a new object, with list.insert(index, object) at a position where it already is an object, the prevous object was replaced!?

But it seems that I have to remove it first with list.removeAt(index) before I can insert the new one, otherwise it was just added and the old left in the list. Is this correct or am I doing something wrong?

Upvotes: 2

Views: 553

Answers (2)

dtb
dtb

Reputation: 217323

The Insert Method inserts a new item at the specified index, making space as needed:

list.Insert(1, "foo");

//  Before              After
//
//  list[0] == "a"      list[0] == "a"
//  list[1] == "b"      list[1] == "foo"
//  list[2] == "c"      list[2] == "b"
//                      list[3] == "c"

If you want to replace an item at a specified index, you can use the list's indexer:

list[1] = "foo";

//  Before              After
//
//  list[0] == "a"      list[0] == "a"
//  list[1] == "b"      list[1] == "foo"
//  list[2] == "c"      list[2] == "c"

See also: Indexers (C# Programming Guide)

Upvotes: 6

angelsl
angelsl

Reputation: 395

This is correct.

But if you wanted to replace an item in the list at a specified index, why not just

list[index] = newitem;

Upvotes: 3

Related Questions