Generic list add null values ​​in C #

I have a generic list called connectedEntites and I add items to that list in a for loop. I am doing a null check before adding. But even when an element is added to this List<>

, a null value is added as well. I debugged, but now null can be added. Because of this null value, when I perform a read operation, the program crashes (since it 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 an image where you can see zero values ​​and the capacity also doubles as the item is added, but the count shows the correct value.

Generic List in Debug Mode

+3


source to share


1 answer


The internal structure List<>

is an array, and arrays are of a given length. This array should grow every time you fill it up by adding elements to List<>

. Capacity

- the actual length of the internal array and is always automatically increased when, Count

after adding, it is equal to the current one Capacity

. It doubles up every time it does it.

If your COM application cannot handle null values ​​in an internal structure (i.e. an array) List<EntityDetails>

, you can use TrimExcess()

these reserved spaces to remove.

From MSDN :



The capacity is always greater than or equal to Count. If the graph exceeds the performance when adding elements, it increases capacity by automatically reallocating the internal array before copying the old elements and adding new elements.

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

+7


source







All Articles