Generic Class:
Generics allow you to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time.
A generic class can be defined using angle brackets <>. For example, the following is a simple generic class with a generic member variable, generic method and property.
Code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace genericClass
- {
- class genericDemo
- {
- public void add<T>(T a, T b)
- {
- dynamic d1 = a; //Dynamic define type in run time.......
- dynamic d2 = b;
- Console.WriteLine(d1+d2);
- }
- public void sub<T>(T a, T b)
- {
- dynamic d1 = a;
- dynamic d2 = b;
- Console.WriteLine(d1 - d2);
- }
- public void mul<T>(T a, T b)
- {
- dynamic d1 = a;
- dynamic d2 = b;
- Console.WriteLine(d1 * d2);
- }
- public void div<T>(T a, T b)
- {
- dynamic d1 = a;
- dynamic d2 = b;
- Console.WriteLine(d1 / d2);
- }
- }
- }
- //Main class....
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace genericClass
- {
- class Program
- {
- static void Main(string[] args)
- {
- genericDemo gDemo = new genericDemo();
- gDemo.add<int>(11,11);
- gDemo.add<double>(11.45, 12.33);
- gDemo.sub<int>(12, 7);
- gDemo.mul<double>(11.45, 12.77);
- gDemo.div<int>(33, 12);
- gDemo.add<string>("Sujan","Hasan");
- Console.ReadKey();
- }
- }
- }
0 Comments:
Post a Comment