fhnaseer
fhnaseer

Reputation: 7277

Best practices for making a 2D array/collection class

I am working on a general library which is going to be widely used in other applications. You can say that it is a kind of SDK library.

I need to implement a 2D collection implementation. It is going to be a generic template abstract class. So what are good practices for making a 2D array or collection. It is like a grid structure.

Here is what I have done for a 1D collection.

public abstract class BaseCollection<T> : Collection<T>

What should I do for 2D collection. [,] or something else.

Upvotes: 2

Views: 2133

Answers (1)

Servy
Servy

Reputation: 203827

There are any number of options, but it will depend in part on what the actual implementation of your 2D collection is.

If you just want a 2D array then there is a special syntax for that. This is a 2D string array:

string[,] twoDimStringArray = new string[4,5];

Another option is to have a list of lists:

List<List<string>> listOfListOfString = new List<List<string>>();

You could have a jagged array:

string[][] arrayOfArraysOfString = new string[5][];

Generally speaking I would discourage you from having a class that extends another collection type. It's generally best to encapsulate another type of collection. If your class is itself exposed as a collection then use the various interfaces that are appropriate, such as IEnumerable, ICollection, IList, ISet, etc.

If you have a two dimensional indexed list-style collection then you could perhaps have your class be an IList<IList<T>>, or an `ICollection>, if you want to expose the level of functionality that those interfaces would (you might not, it's hard to tell without knowing more of the context).

Upvotes: 1

Related Questions