Initialize an Indexer Class

49 views Asked by At
    public class myCollection<T> {
        private T[] arr = new T[100];
        
        public T this[int i] {
            get { return arr[i]; }
            set { arr[i] = value; }
        }
    }

with this simple example the array type of myCollection for type string gets automatically sized to 100 . My specific question is how to be flexible if I only need 10 or 25 in size to not waste memory if less than 100 needed or even more. How to escape of this fixed size by parameter ?

1

There are 1 answers

1
David On BEST ANSWER

Add a constructor that lets you provide the value you want:

public class myCollection<T> {
    private T[] arr;
    
    public T this[int i] {
        get { return arr[i]; }
        set { arr[i] = value; }
    }

    public myCollection(int size) {
        arr = new T[size];
    }
}

If you still want a parameterless constructor, you can chain one which still defaults to 100 when no value was specified:

public class myCollection<T> {
    private T[] arr;
    
    public T this[int i] {
        get { return arr[i]; }
        set { arr[i] = value; }
    }

    public myCollection(int size) {
        arr = new T[size];
    }

    public myCollection() : this(100) { }
}