C # When call remove is invalidated

Source: Internet
Author: User

Have you ever tried to remove an object from a collection and the collection still has this object? The world is big and wonders. A slight negligence will lead to this strange phenomenon. Now let's see what this "Undead" object is all about.

1, "Not Dead" object appeared

This question was originally proposed by one of my colleagues, to reproduce the "undead" object, the code is simplified as follows:

Code #01

IList products = new List<Product>();
products.Add(GetProduct("1412"));
products.Remove(GetProduct("1412"));

Where the Product class code is as follows:

Code #02

class Product
{
  public Product(string id)
  {
    m_ID = id;
  }

  private string m_ID;
  public string ID
  {
    get { return m_ID; }
  }

  public override string ToString()
  {
    return "ID: " + m_ID;
  }
}

The GetProduct method reads the data from the database and returns it based on the incoming ID, and its signature is as follows:

Code #03

public static Product getproduct (string id);

To see whether an object with number 1412 is removed from the products, simply add one line to the end of the code #01:

Code #04

Console.WriteLine (Products. Count);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.