public class List<T>
{
public int Count
{
get;
}
}
I noticed Count
is an int
, will the result be less than 0?
If Count
could be less than 0
, I have to write that:
if(myList.Count < 1)
{
}
otherwise I can write that:
if(myList.Count == 0)
{
}
From the comments:
Just to be on the safe side, because I noticed the Count is a
int
but not auint
When the List<T>
class was designed, Microsoft's .NET class library design rules meant that UInt32
(aka uint
) could not be used for any public
members, so instead Int32
(aka int
) was used.
Count
is an int
(aka Int32
) property instead of a uint
(or UInt32
) property is because the List<T>
type was defined when the Common Language Specification (the "CLS") was still being respected by Microsoft.
Int32
is CLS-compliant.UInt32
is not CLS-compliant.Count
was typed as UInt32
instead of Int32
then users of those other languages couldn't use List<T>.Count
at all.List<T>.Count
ever be negative or otherwise invalid?Provided you use a List<T>
instance in a safe manner, then no, the .Count
property will always return a value in the range 0
to 2^31
(the actual maximum count of a List<T>
is a different question which is already answered here).
However, if you use a List<T>
in a thread-unsafe manner (such as having 2 or more threads concurrently adding and removing items from a list without using lock
correctly), or if you use tricks like reflection to override the .Count
property's field value then yes, you can break things. So don't do that :)
The motivation for the CLS is described in this article:
- To enable full interoperability scenarios, all objects that are created in code must rely on some commonality in the languages that are consuming them (are their callers).
- Since there are numerous different languages, .NET has specified those commonalities in something called the Common Language Specification (CLS).
The Common Language Specification is described in this MSDN article, which has a list of types built-in to .NET but which are verboten for use in CLS-compliant frameworks and redistributable libraries.
System.SByte
aka sbyte
.
System.UInt16
aka ushort
.System.UInt32
aka uint
.System.UInt64
aka ulong
.System.UIntPtr
.Also:
- The rules for CLS compliance apply only to a component's public interface, not to its private implementation.
- For example, unsigned integers other than
Byte
are not CLS-compliant [...].