I've created a List with fixed size
private List<ushort> responseData = new List<ushort>(7);
Items are added on a reactive observable but I would like to know if it's full on each subscribe.
Currently It is checked by
if (responseData.Count == 7)
Since responseData size will be dynamic, I won't be using the static 7 in both initialisation of List and checking if it's full. However, I was just wondering if I set responseData size already; Can't it check without using the size reference again?
I highly value any response.
If I understand correctly, you might be thinking of the List<T>.Capacity property?
When you initialise a List, you can specify the internal capacity which indicates the number of items that can be added to a List before a resize needs to take place. The default is 4 for the list capacity [used to be, needs confirmation it still is].
So, if you create a new list as such:
var myList = new List<int>(100);
You could create an extension method that adds and checks for you:
public static class ListExtension
{
public static bool Add<T> ( this List<T> list, T item, out bool isFull )
{
isFull = false;
if ( list.Count == list.Capacity )
{
isFull = true;
return false;
}
list.Add ( item );
isFull = list.Count == list.Capacity;
return true;
}
}
Now, this is stated in the Microsoft docs:
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.
Therefore, the extension method should only ever allow you to add items up to the initial Capacity, and no more. When used like this, var success = myList.Add(item, out var isFull), isFull will indicate whether the list is full. The return value will indicate whether the operation was successful.