Program to Add any two types using Generics.
This program is used to perform addition between any two types or concat between two strings using single method with Generics.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; using System.Collections.Generic; namespace Generics { public class MyClass<T> { public T a; public T b; public void test(T i,T j) { a = i; b = j; Console.WriteLine(i.GetType()); } } public class test1 { public void Add<T>(T a, T b) { dynamic i = a; dynamic j = b; Console.WriteLine(i+j); } } class Program { static void Main(string[] args) { test1 t = new test1(); t.Add<int>(10,20); t.Add<string>("tushar"," patel"); } } } |
Note:Here in the add method we have declared variables i and j as dynamic because their types are not known at compile time and are inferred at run time.And an dynamic variable can change it's type at run time. Ex. dynamic i =100; In this case i will initialized to 100 so it will be int32 type.But in case at run time a string is assigned to it then it will become string type And if we talk about usage of dynamic, it is mostly used to make properties and return value from function
Comments
Post a Comment