C generic array learning summary

  • 2020-05-07 20:15:05
  • OfStack

C# generics and arrays in C# 2.0, 1-dimensional arrays with a lower limit of zero automatically implement IList < T > . This allows you to create generic methods that can access arrays and other collection types using the same code loop. This technique is primarily useful for reading data from collections. IList < T > Interfaces cannot be used to add or remove elements from an array; If you try to call IList in this context < T > Methods, such as RemoveAt for groups of Numbers, throw an exception. The following code example demonstrates with IList < T > How a single generic method of an input parameter loops through both a list and an array, in this case an array of integers.

C# generics and array code

 
class Program 
{ 
static void Main() 
{ 
int[] arr = { 0, 1, 2, 3, 4 }; 
List<int> list = new List<int>(); 
for (int x = 5; x < 10; x++) 
{ 
list.Add(x); 
} 
ProcessItems<int>(arr); 
ProcessItems<int>(list); 
} 
static void ProcessItems<T>(IList<T> coll) 
{ 
foreach (T item in coll) 
{ 
System.Console.Write(item.ToString() + " "); 
} 
System.Console.WriteLine(); 
} 
} 


Notice when applying C# generics and arrays

Although the ProcessItems method cannot add or remove items, the IsReadOnly property returns False for T[] inside ProcessItems, because the array itself does not declare the ReadOnly property.

So much for C# generics and arrays. I hope this will help you learn about C# generics and arrays.

Related articles: