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?

Community
  • 1
  • 1
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
  • 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. – Dave F Dec 24 '21 at 17:33

2 Answers2

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.

Joe
  • 122,218
  • 32
  • 205
  • 338
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.

elder_george
  • 7,849
  • 24
  • 31
  • 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. – Slothario Nov 22 '18 at 17:01