18

Possible Duplicate:
count vs length vs size in a collection

In .NET, pretty much all collections have the .Count property.

Sometimes I wonder if it would be better to have it on Array as well, directly though, not through ICollection.

It's just something you make an exception in your mind only for arrays.

So is it better to be "more correct" or "more uniform" in this case?

1
  • Side effects from using similar code in .NET languages should also be considered. In C# using Length incorrectly will throw an error because it either isn't available or it returned the wrong type of data. In PowerShell, Count and Length produce the same result for arrays, but collection objects don't return the expected result for Length. For example, ([ordered]@{'a' = 0; 'bc' = 0;'def' = 0;}).Keys.Length returns 1,2,3 and not 3. This is because Length returns a list of Length properties for each key, which is the length of each string. Commented Dec 24, 2021 at 17:33

2 Answers 2

9

In many cases where a one-dimensional array is used, it's essentially being used as a fixed-size list.

Personally I will often declare an array as IList<T>, and use the Count property rather than Length:

IList<string> strings = new string[] { ...};

Another useful member of IList<T> that does not exist in Array is the Contains() method.

Sign up to request clarification or add additional context in comments.

Comments

3

If you're using C# 3.0, you may use Enumerable.Count() extension method that works on all IEnumerable implementations, including lists, arrays and dictionaries.

It causes some overhead, but it's usually tolerable.

1 Comment

If there's any chance at all, though, that you're working on a critical code path that could be executed a lot of times, you need to understand what the Count() method is doing. It can get hairy if you're running some kind of LINQ query and you want to count how many items are in the database -- Count() will actually pull down all the data and enumerate through every element. Very inefficient for large data sets.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.