Array : Array is strong type because there is no boxing and unboxing. It's performance is better than other collection.But there is a weak point is that it is a fixed length.
And ArrayList and HashTable is resizable but weak point is that it takes only objects and then It has more boxing and unboxing.
After reading above both line software developers think that, we have read any thing there is some lackess is very topic or every where.
I think one question is arising in software developers mind that if C# provide any other collection which fulfill both above lackness.
Now software developers want to take advantage of both then one picture comes in mind That is Generic Collection. Generic collection help us to create strong, flexible type collection easy.
First we are talking about Generics then Generic Collection.
Generics are the most power features in C# 2.0 .
Generics allow you to define type-safe classes without compromising type safty, performance or productivity. Generic introduce to the .NET Framework the concept of type parameter, which make it possible to design classes and methods.
Example: I want to compare two values first I will do it with simple class after that we will do it by using Generic .
Let’s try to understand by a practical example.
Open Visual Studio.
Click on Project and set the name Application is MyFirstGenericApplication
Now try to use first method means simple class
Add a Check Class
- public class Check
- {
- public bool Compare(int a, int b)
- {
- if (a == b)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Check objCheck = new Check();
- bool result = objCheck.Compare(1, 4);
- Console.Write(result);
- Console.ReadKey();
- }
- }
Output:
As you see above for compare two integer numbers I have to create Compare function, think about if I want to compare two string or two float values then I have to create seperate method for each. So solve this issue Generic comes.
Generic allow to define the classes or function of any type.
If I define a class of any type and compare function parameter's type is any type(REPLACEDTATYPE), then If I have pass integer datatype in class type at runtime then parameter type is also integer type or pass string type then parameter type is also string. It will happen using Generic Collection then we must have to add reference of Using System.Generic.Collections in our project.
I have create same class with Class with type and function parameter with also type.
- public class Check <REPLACEDATATYPE>
- {
- public bool Compare(REPLACEDATATYPE a, REPLACEDATATYPE b)
- {
- if (a.Equals(b))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
Now create and object of Check class then is showing compile time error which you can see below..
Leave Comment