Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Count() method use the "checked" keyword?

Tags:

As I was looking the difference between Count and Count(), I thought to glance at the source code of Count(). I saw the following code snippet in which I wonder why the checked keyword is necessary/needed:

int num = 0; using (IEnumerator<TSource> enumerator = source.GetEnumerator()) {     while (enumerator.MoveNext())     {         num = checked(num + 1);     }     return num; } 

The source code:

// System.Linq.Enumerable using System.Collections; using System.Collections.Generic;  public static int Count<TSource>(this IEnumerable<TSource> source) {     if (source == null)     {         ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);     }     ICollection<TSource> collection = source as ICollection<TSource>;     if (collection != null)     {         return collection.Count;     }     IIListProvider<TSource> iIListProvider = source as IIListProvider<TSource>;     if (iIListProvider != null)     {         return iIListProvider.GetCount(onlyIfCheap: false);     }     ICollection collection2 = source as ICollection;     if (collection2 != null)     {         return collection2.Count;     }     int num = 0;     using (IEnumerator<TSource> enumerator = source.GetEnumerator())     {         while (enumerator.MoveNext())         {             num = checked(num + 1);         }         return num;     } } 
like image 520
snr Avatar asked Mar 25 '20 13:03

snr


People also ask

How does count work C#?

In its simplest form (without any parameters), the Count() method returns an int indicating the number of elements in the source sequence. IEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count();

What is the difference between count and count () in C#?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values.


1 Answers

Because it doesn't want to return a negative number in the (admittedly unlikely) event that there are more than 2-billion-odd items in the sequence - or a non-negative but just wrong number in the (even more unlikely) case that there are more than 4-billion-odd items in the sequence. checked will detect the overflow condition.

like image 139
Marc Gravell Avatar answered Oct 14 '22 09:10

Marc Gravell