Search This Blog

Thursday, November 28, 2013

Generics and Arrays Example in C#

C# > Generics > Generics and Arrays

Example: Use a single generic method that takes an IList<T> input parameter and iterate through both a list of integers and an array of string.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] str = { "0", "1", "2", "3", "4" };
            List<int> intL = new List<int>();
            for (int x = 0; x < 5; x++)
            {
                intL.Add(x);
            }
            ProcessList<string>(str);
            ProcessList<int>(intL);
        }
        static void ProcessList<T>(IList coll)
        {
            foreach (T item in coll)
            {
                MessageBox.Show(item.ToString());
            }
        }
    }
}