For example i have this C# method :
public static int Count<T>(IEnumerable<T> sequence)
{
return 0;
}
Why i have to write Count<T>
rather than Count
even when i'm not using the T
type inside the method ?
You don't have to. You could go entirely non-generic:
public static int Count(IEnumerable sequence)
{
return 0;
}
And since IEnumerable<out T> : IEnumerable
, this will work for all sequences.
One reason not to do this, however, is that if you plan to do:
int count = 0;
foreach(var obj in sequence) count++;
return count;
then the non-generic version when used with value types will box every value - increasing allocations. The generic version will not do any boxing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.