Search code examples
c#objectself-destruction

How to make a object delete itself from a list.


So I have some objects in a list. I want to make my object to have a method that when called will delete itself from the list. How could I do that?


Solution

  • Is this a trick question?

    public class MyObject
    {
        public void RemoveFromList(List<MyObject> list)
        {
            if (list == null)
                return;
    
            list.Remove(this);
        }
    }