Reputation: 1
I have created an array with a predefined length of 2. And I have a method for adding items to the array.
The code for it is:
public void addItem(T item)
{
Array.Resize(ref items, items.Count() + 2);
items[items.Count() - 2] = item;
}
Now, what I want to do is that it first has to check the array size and see if the array is full of not. If the array is full, it should double the size of the array. If its not full then it shouldn't do nothing. So, I'm wondering if I can make this possible with an if statement?
EDIT: Im writing an collection class, thats why I need to check the array
Upvotes: 0
Views: 140
Reputation: 459
You should know, that you do not learn anything, if you do not do your homework on your own
but try something like this:
if count > size -2 than resize: size*2 else //do nothing
maybe you can add a feature like: if count < size / 4 than shift entries to the front and resize: size/2 else //nothing
hope this advise is useful for you
Upvotes: 0
Reputation: 460038
You should really get familiar with the List<T>
which already uses this functionality by default:
List.Add
for example calls EnsureCapacity
:
private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}
Upvotes: 1