Saturday, June 27, 2015

Generic Class in C#

Generic Classes have type parameters. Using Generic Classes a developer can encapsulate the operations which are not of specific data type.

Here is the Example to understand the same:

Example 1:

using System;

namespace GenericClass
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass<int> mc = null;
            MyClass<string> mc1 = null;
            try
            {
                mc = new MyClass<int>(10);
                Console.WriteLine(mc.PrintThis());
                mc1 =new MyClass<string>("Hello World.");
                Console.WriteLine(mc1.PrintThis());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                mc = null;
                mc1 = null;
            }
            Console.ReadLine();
        }
    }
    class MyClass<T>
    {
        private T _Value;
        public MyClass(T t)
        {
            _Value = t;
        }
        public string PrintThis()
        {
            return "You Passed : " + _Value;
        }
    }

}

Output will be :