Suppose you have a list of objects and the object has a Destroy method and one of its job is to remove itself from the list. Remembering your index number won't do it because some other object may have been removed which will change the index number. What's the best way to do this?
Asked
Active
Viewed 43 times
0
-
2Why is its job to remove itself? – mason May 31 '19 at 16:18
-
1Have you tried anything? Index numbers aren't a big deal in lists either. – Dortimer May 31 '19 at 16:19
-
1You can pass an object to `List.Remove`, you don't need an index number. – Blorgbeard May 31 '19 at 16:19
-
The object x is a very complex structure and the Destroy method does many consequential things and, as its last act, it would be nice if it could remove itself from the list. – Bing Bang May 31 '19 at 16:30
-
@Dortimer I didn't know you could do that. Doesn't this mean you can say this.Remove(); inside my Destroy method? I'm a lifelong C programmer trying to learn C#. – Bing Bang May 31 '19 at 16:45
-
1@BingBang I think you'd probably be better off having code outside the list managing `.Remove()`'s and so on. I believe `.Remove()` calls the object's destructor, so you could probably handle whatever you need in there. One note: if you're looping through a list with `foreach` you can't make modifications to the list. So you'll have to use a traditional `for` loop. – Dortimer May 31 '19 at 16:52
-
@Blorgbeard So in the Destroy object I can say List.Remove(this); ? – Bing Bang May 31 '19 at 16:52
-
@Blorgbeard method, not object – Bing Bang May 31 '19 at 16:56
-
2If it holds a reference to the list, then yes, it can do that. I do think the design is a bit smelly though. – Blorgbeard May 31 '19 at 16:56
-
@Blorgbeard Yes, well, I have a ways to go. – Bing Bang May 31 '19 at 16:59