user2167085
user2167085

Reputation: 1

Checking current value of an array, C#

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

Answers (2)

Anton
Anton

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

Tim Schmelter
Tim Schmelter

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

Related Questions