C#2, Arrays and generics

I discovered today that a single dimensional array automatically implements a generic IList<T> interface; this means we can write the following code :
 
    class Program
    {
        static void Main()
        {
            int[] arr = new Int[10];
            ….
            ar[5] = 5;
            …   
            ProcessItems<int>(arr);
        
        }
        static void ProcessItems<T>(IList<T> coll)
        {
            foreach (T item in coll)
            {
                System.Console.Write(item.ToString() + " ");
            }
            System.Console.WriteLine();
        }
    }
Advertisements

One response to “C#2, Arrays and generics

  1. using System;
    using System.Collections.Generic;
    using System.Text;
    namespace ConsoleApplication2
    {
    class Program
    {
    static void Main()
    {
    int[] arr = new int[10];

    arr[5] = 5;

    Program.ProcessItems<int>(arr);

    }
    static void ProcessItems<T>(IList<T> coll)
    {
    foreach (T item in coll)
    {
    System.Console.Write(item.ToString() + " ");
    }
    System.Console.WriteLine();
    }
    }
    }
    Very good

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s