简体   繁体   中英

Generic list adds null values in c#

I have a generic list called connectedEntites and I add items to this list in a for loop. I do a null check before adding. But even then whenever an item is added to this List<> a null value is also added. I did debug but there is noway a null value can be added. Due to this null value when i perform read operation the program crashes (as this is a COM program).

Below is the code for the class

public class EntityDetails
{
    public ObjectId objId { get; set; }
    public Handle objHandle { get; set; }
    public string className { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        EntityDetails objAsEntityDetails = obj as EntityDetails;
        if (objAsEntityDetails == null) return false;
        else return Equals(objAsEntityDetails);
    }

    public bool Equals(EntityDetails other)
    {
        if (other == null)
            return false;

        return (this.objId.Equals(other.objId));
    }
}`

Below is the image where you can see the null values and the capacity also doubles as the item is added, but the count shows correct value.

调试模式下的通用列表

The internal structure of a List<> is an array and arrays have a specified length. This array needs to grow each time you fill it up by adding items to the List<> . The Capacity is the actual length of the internal array and is always automatically increased when the Count after adding equals the current Capacity . It doubles each time it does so.

If your COM application cannot handle the null values in the internal structure (ie the array) of the List<EntityDetails> you can use TrimExcess() to delete those reserved spaces.

From MSDN :

Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new elements.

See also this question: List<> Capacity returns more items than added

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM