Generics
Before we start learning What Generics is ? , let me explain what problem generics came to solve .
In .NET version 1 , we don't have generics .So ,lets say we need to create a list to store a list of numbers . The implementation of that class looks like below :
Currently , as I am not concentrating on how data structures works , just assumed a sample list class with only Add method , which add the passed integer into its list. Rather than defining all the methods like Remove , find and properties and functionality and so on , just planned to have my class and projected on how generics came into existence .
Let me define a simple class object here :
Now , if i plan to store a book to the list defined above it doesn't work as int is a value type and our book class will be a reference type . So , I am forced to create some class like below, which will give the ability to add a list of books :
So , the code is not reusable , so one solution to fix this is we can go with Object , which is parent class for every class in .NET.
But this too has an issue and that is performance . The value type like int uses boxing (while stored) and unboxing (accessed) every time and for reference type it uses casting to perform on the class . To solve this issue is where generics came into action .
Generic usage is something which looks like below :
So , here for T we can pass any type of class i.e even a value type(int) or a reference type(book) or another data types . So generics is a class defined once and reused .This is the basics of creating a generic list . In practical terms most often you will be using generics as opposed to creating ones.
Most often we use the one the generics list offered in .NET . Some of such predefined generic list in .NET are Dictionary , LinkedList and some interfaces like IEnumerable , IList , IDictionary and so on.
So , this is the history of generics , but in the next section we can see how we can create a generic in real time if the application you are working on forces you to do so .
Concepts are well explained
ReplyDelete