3

In order to to get the number of subitems in dotnet sometimes i have to ask a property Lenght sometimes i have to ask a property Count.

Is there any reason for the distinction?

example:

   int[] a; if (a.Length == 0) ....
   IList<int> b; if (b.Count == 0) ....

Note Difference between IEnumerable Count() and Length sounds similar but does not answer the semantic between Length and Count

Community
  • 1
  • 1
k3b
  • 14,517
  • 7
  • 53
  • 85
  • see this in fact: http://stackoverflow.com/questions/300522/count-vs-length-vs-size-in-a-collection – nawfal Apr 19 '12 at 04:27

5 Answers5

5

I can't quote a source, but I think that a .Length is a fixed value and a .Count can change.

You can't change the number of items in an array once it is created, so that has a .Length.

You can add to (or remove from) a List, so that has a .Count.

EDIT
So a .Length:

  • Will not change for this object
  • Should involve just a quick lookup of an internal value

While a .Count or .Count():

  • Might change for this object
  • Might involve an iteration over the internal items (depending on the implementation)
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • Sounds reasonable. Same applies to string.Length since the string cannot be changed. The Stringbuilder is mutable but it has Length property – k3b Dec 09 '10 at 11:47
3

Semantically, an array has a constant number of elements, it has a length, therefore the property is called Length. A list has variable number of elements, and if you want to know how many elements are there, you need to count them, therefore the Count name.

Andrei Pana
  • 4,484
  • 1
  • 26
  • 27
2

Length is an array property, Count an ICollection one and Count() a method on IEnumerable, but aside from that, they mean the same.

That is, they hold that number of items in the collection.

Note: in the case of IEnumerable, the Count() method can (and normally will) iterate over all items in the collection in order to obtain a count. The properties will simply return a value.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

There's no semantic difference. It just a framework design detail that we should deal with.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

I can remember the Framework Design Guidelines contains an annotation about this difference (I will at a qoute of it tomorrow). What I recall is that the designers think this is a quirk in the design, because it doesn't make sense for a lot of developers. Remember that in the beginning there were no design guidelines for .NET and much of the .NET API was copied from Java, including the quirks.

Steven
  • 166,672
  • 24
  • 332
  • 435