This program defines a method Display
that takes an IList<int>
(an interface for a list of integers) as its parameter. The Main
method creates an array of integers and a List<int>
object, and it calls the Display
method with each of these objects as its argument.
The Display
method uses the Count
property of the IList<int>
interface to print the number of elements in the list, and it uses a foreach loop to iterate through the elements of the list and print each one.
The Main
method first calls Display
with an array of integers as its argument. Then it calls Display
with a List<int>
object as its argument. In both cases, the Display
method is able to work with the parameter as if it were a list of integers, even though the actual type of the object being passed as an argument is different. This is an example of polymorphism, where a method can work with multiple types of objects in a similar way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using System; using System.Collections.Generic; class Program { static void Main() { int[] a = new int[3]; a[0] = 1; a[1] = 2; a[2] = 3; Display(a); List<int> list = new List<int>(); list.Add(5); list.Add(7); list.Add(9); Display(list); Console.ReadLine(); } static void Display(IList<int> list) { Console.WriteLine("Count: {0}", list.Count); foreach (int num in list) { Console.WriteLine(num); } } } |