What is generics ?
Generics is c# features which allow to define a class or method with type as a parameter.
In generics we can define a type at the time of declaration and initialization.
Facts about Generics.
- We can use generics types to maximize code reuse. type safety and perfomance.
- We can create your own generic interfaces, classes, methods, events and delegates.
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | using System; namespace PracticleTest { class Program { static void Main(string[] args) { // String and int array list int[] intarray = new int[] { 1, 15, 55, 4, 31 }; string[] strarray = new string[] { "Bengaluru", "Ahmedabad", "Pune", "Mumbai" }; // Without Generic Method Sort About int and string array. // We need to call two different method for different data type. sortingdemo obj = new sortingdemo(); // Sort String array we need to call "sortstringarray" methods. string[] stroutputarray = obj.sortstringarray(strarray); // Sort int array we need to call "sortintarray" methods. int[] intoutarray = obj.sortintarray(intarray); // Using Generic Method // We can reuse the code by using generic methods. // generic methods are always static. int[] genericintarray = sortingdemo.sortgeneric(intarray); string[] genericstringarray = sortingdemo.sortgeneric(strarray); } public class sortingdemo { public string[] sortstringarray(string[] strarray) { // Using Sort function. string[] aryoutput; aryoutput = strarray; Array.Sort(aryoutput); return aryoutput; } public int[] sortintarray(int[] intarray) { int[] aryintout; aryintout = intarray; Array.Sort(aryintout); return aryintout; } public static T[] sortgeneric<T>(T[] array) { T[] arryout; arryout = array; Array.Sort(arryout); return arryout; } } } } |