Reputation: 14755
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
Upvotes: 3
Views: 222
Reputation: 39284
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
:
While a .Count
or .Count()
:
Upvotes: 5
Reputation: 172676
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.
Upvotes: 1
Reputation: 4502
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.
Upvotes: 3
Reputation: 499072
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.
Upvotes: 2
Reputation: 1038930
There's no semantic difference. It just a framework design detail that we should deal with.
Upvotes: 2