C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# GenericsGeneric is a concept that allows us to define classes and methods with placeholder. C# compiler replaces these placeholders with specified type at compile time. The concept of generics is used to create general purpose classes and methods. o define generic class, we must use angle <> brackets. The angle brackets are used to declare a class or method as generic type. In the following example, we are creating generic class that can be used to deal with any type of data. C# Generic class exampleusing System; namespace CSharpProgram { class GenericClass<T> { public GenericClass(T msg) { Console.WriteLine(msg); } } class Program { static void Main(string[] args) { GenericClass<string> gen = new GenericClass<string> ("This is generic class"); GenericClass<int> genI = new GenericClass<int>(101); GenericClass<char> getCh = new GenericClass<char>('I'); } } } Output: This is generic class 101 I C# allows us to create generic methods also. In the following example, we are creating generic method that can be called by passing any type of argument. Generic Method Exampleusing System; namespace CSharpProgram { class GenericClass { public void Show<T>(T msg) { Console.WriteLine(msg); } } class Program { static void Main(string[] args) { GenericClass genC = new GenericClass(); genC.Show("This is generic method"); genC.Show(101); genC.Show('I'); } } } Output: This is generic method 101 I
Next TopicC# Delegates
|