Generics
- Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type
- Generic 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.
- To 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.
Generic Class Example
class GenericExamples
{
class GenericDemo<T>//Create Generic class
{
public GenericDemo(T args)//Create Constrtuctor
{
Console.WriteLine("Generic value - {0} ", args);
}
}
public static void Main(String[] args)
{
GenericDemo<string> gd = new GenericDemo<string>("Hello This is String");//passed string param
GenericDemo<int> gd1 = new GenericDemo<int>(1);//Passed Int param
Console.ReadLine();
}
}
Output:
Generic value - Hello This is String
Generic value - 1
You can see on above example that we have passed different parameter to class and it's working with that. still if you have any doubts please ask me in comment box.
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.
Example
class GenericExamples
{
class GenericDemo
{
public void Play<T>(T args)//Create Generic method
{
Console.Write("{0} ", args);
}
}
public static void Main(String[] args)
{
GenericDemo gd = new GenericDemo();
gd.Play("There are");
gd.Play(11);
gd.Play("Players in cricket");
Console.ReadLine();
}
}
Output:
There are 11 Players in cricket
Features of Generic
- It helps you to maximize code reuse, type safety, and performance.
- You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace.
- You can create your own generic interfaces, classes, methods, events, and delegates.
- You may create generic classes constrained to enable access to methods on particular data types.
- You may get information on the types used in a generic data type at run-time by means of reflection.
No comments:
Post a Comment
Please let me know if you have any feedback or doubts.