vendredi 8 mai 2015

What are the benefits and drawbacks of indexer methods in C#?

I have a collection class that implements an indexer method like so:

public class ProductCollection : IEnumerable {
    private ArrayList products = new ArrayList();

    public Product this[int index] {
        get { return (Product)products[index]; }
        set { products.Insert(index, value); }
    }

    public int Count {
        get { return products.Count; }
    }

    public IEnumerator GetEnumerator() {
        return products.GetEnumerator();
    }
}

It allows me to manipulate its elements using indexes, just like a standard array:

ProductCollection collection = new ProductCollection();
collection[0] = new Product {Description = "Product 1"};
collection[1] = new Product {Description = "Product 2"};

for (int index = 0; index < collection.Count; index++) {
    Console.WriteLine(collection[index].Description);
}

Alternatively, I could have the same collection without the indexer method by implementing simple Add and Get methods. It would look like this:

public class ProductCollection : IEnumerable {
    private ArrayList products = new ArrayList();

    public void Add(int index, Product product) {
        products.Insert(index, product);
    }

    public Product Get(int index) {
        return (Product)products[index];
    }

    public int Count {
        get { return products.Count; }
    }

    public IEnumerator GetEnumerator() {
        return products.GetEnumerator();
    }
}

Then I could perform the same operations as before, only with a slightly modified syntax:

ProductCollection2 collection = new ProductCollection2();
collection.Add(0, new Product {Description = "Product 1"});
collection.Add(1, new Product {Description = "Product 2"});

for (int index = 0; index < collection.Count; index++) {
    Console.WriteLine(collection.Get(index).Description);
}

Keeping syntax aside and considering the internals of the language, are there any benefits and/or drawbacks of using one form or another?

Aucun commentaire:

Enregistrer un commentaire