Monday 25 January 2016

Generic Class Collection Example in C#

A small example without function overloading which will show how generic are working in c#.

       
using System;
using System.Collections.Generic;

public class Generic_Class_Collection
{

    static void printArray<T>(object obj)
    {
        if (obj is int[])
        {
            var arr = (Int32[])obj;
            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }
        }
        else if (obj is string[])
        {
            var arr = (string[])obj;
            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }
        }
    }
    
    static void Main(string[] args)
    {
        int[] vInt = new int[] { 1, 2, 3 };
        string[] vString = new string[] { "Hello", "World" };

        printArray<int>(vInt);
        printArray<string>(vString);

        Console.Read();
    }
}