Using Generics With
C#
Generics are most
frequently used with collections and the methods that operate on them. Version
2.0 of the .NET Framework class library provides a new namespace,
System.Collections.Generic, which contains several new generic-based collection
classes.
Generics are different from generic collections. Generic
collections are emerged from generic concept. It helps us to maximize code
reuse, performance and type safety.
Generics are strongly type collections.
Generics help to decouple the data-type from the logical
code snippet which makes the code to reuse again and again.
We can also create classes and pass to it the generic
parameter as type.
We can use generics in our code by calling the namespace
"using System.Collections.Generic;".
Microsoft applied generic concept on
.NET collections to make generic collections.
Arraylist to make list generic collections.
Hashtables to make Dictionary.
Stacks and Queues to make Stacks and Queues generics.
Example: public class GenericsClass<T>
{
public bool Compare(
T a , T b)
{
if(a.Equals( b))
{
return true;
}
return false;
} }
}
class Program
{
public static void
Main()
{
GenericsClass<int> obj
= new GenericsClass<int>();
bool checkintData =
obj.Compare(10, 10);
Console.WriteLine("Int data Check:{0}", checkintData);
GenericsClass<string> obj1
= new GenericsClass<string>();
bool StringData = obj1.Compare("indian", "indian");
Console.WriteLine("String
data Check:{0}", StringData); }
}
OutPut : True, True
Advantages of Generic:
Type safety -
this ensures that the method, class, or interface etc. works only on the
correct data type. For example, if you use string when calling a generic
method, then all the values passed in as expected to be strings. If you pass in
an int value parameter, the compiler will detect that as an error and the
program will not be able to compile.
Errors/Exceptions are
caught at compile time as opposed to runtime errors/exceptions - if given a
choice between compile time and runtime errors, 100% of developers choose
compile time errors so should you. The last thing we want is errors crashing
the program when the users are working with it.
Re-usability &
Flexibility - in the above example on the problem statement, we declared
more than one method and the only difference was the data type of the
parameters that we passed. With generics, you only have to create one method
and re-use it with any data type that you want
Write clean code
- we do not need to write methods, class or interfaces that contain complex
logic that checks the data type of the parameter values passed in.
0 comments :
Post a Comment