Santosh
Santosh

Reputation: 127

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.

Generic List in Debug Mode

Upvotes: 2

Views: 2464

Answers (1)

pyrocumulus
pyrocumulus

Reputation: 9290

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 (i.e. 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

Upvotes: 6

Related Questions