What is Generics?
Yogesh Jadhav
Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here: // Declare the generic class.public class GenericList{ void Add(T input) { }}class TestGenericList{ private class ExampleClass { } static void Main() { // Declare a list of type int. GenericList list1 = new GenericList(); // Declare a list of type string. GenericList list2 = new GenericList(); // Declare a list of type ExampleClass. GenericList list3 = new GenericList(); }}
Generics are the type safe programs. We can reduce the code.We can pass datatypes at Runtime. Ex: private T[] Sort(T[] input) {return input; }
Java generics were introduced in 2004 with Java 5. It has been around for eight years now, but Java generics still pose problems for experienced developers and newcomers alike. Beginners often find Java generics to be counterintuitive. I think it must be difficult to learn Java generics if you don't have the pre-generics perspective first. It's hard to understand some of Java generics' limitations if you don't have a firm grasp of Java code without generics. Experienced developers often have only a rough idea of what Java generics do. They don't want to dig into the details and are often surprised by generics behavior.
Generics allow you to define type-safe data structures, without committing to actual data types.generics are similar to C++ templates, but are drastically different in implementation and capabilities.By using this concept you get to reuse data processing algorithms without duplicating type-specific code.