Showing posts with label C# generic. Show all posts
Showing posts with label C# generic. Show all posts

Monday, January 18, 2016

Generic in C# with example?



Generic can be defined as <T> sign after the class name, by using the generic there is no need of boxing and unboxing. Generic also can be implemented with interfaces, delegates and methods.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class Class1<T>
    {
        T i;
        public T prop1
        {
            get
            {
                return i;
            }
            set
            {
                i = value;
            }
        }
    }
}


Code on button click:
Class1<int> obj = new Class1<int>();
        private void button1_Click(object sender, EventArgs e)
        {

            obj.prop1 = 100;
            int x = obj.prop1;
            MessageBox.Show(x.ToString());
        }

Output : 100