0

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

7
  • 9
    Sounds like you are reinventing the List<T> class? May I ask why? Commented Mar 14, 2013 at 9:14
  • 2
    Why don't you use a List<T> is has this functionality already built-in? Commented Mar 14, 2013 at 9:14
  • reinventing wheel is a serious business Commented Mar 14, 2013 at 9:15
  • Im creating an Collection class, thats why Commented Mar 14, 2013 at 9:15
  • 1
    I guess this is homework, which is why he can't use the built-in stuff. Commented Mar 14, 2013 at 9:19

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but I am writing an collection class and Im not allowed to use the generic collections
So is this homework. Ok, but it's not clear what problem you actually have. You could look at the implementation of List<T>(i used ILSpy) to see how MS did it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.