In this article, We will learn about Generics in C#.
e.g.
TypeName<T>
Where T is a Type Parameter.
Generic Class
Generic classes are defined by using a type parameter in angle brackets after the class name.
Syntax,
Class class_name<T> { public T property_name {get; set;} }
Example :
Class Employee<T> { public T EmployeeNo {get; set; } public T SalaryCalculation() { //write code here… } }
Above, the Employee is a generic class. T is called a type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the Employee class.
For example,
Note:
You can also define multiple type parameters separated by a comma.
Example:
Class MultiType<Tkey, Tvalue> { public Tkey No {get; set; } public Tvalue Name {get; set; } }
Instantiating Generic Class
You can create an instance of generic classes by specifying an actual type in angle brackets.
For example,
The following creates an instance of the above created a generic class Employee.
Employee<int> emp = new Employee<int>(); emp.EmployeeNo = 116;
Above, we specified the int type in the angle brackets while creating an instance. So, T will be replaced with an int type wherever T is used in the entire class at compile time. Therefore, the type of EmployeeNo property would be an int, and the return type of SalaryCalculation Method will be int.
You can assign an int value to the EmployeeNo property. Trying to assign values other than int will result in a compile-time error.
Employee<int> emp = new Employee<int>(); emp.EmployeeNo = 116; //emp.EmployeeNo = “Hello World”; //compile-time error
You can specify the different data types for different objects, as shown below.
Employee<string> emp = new Employee<string>(); emp.EmployeeNo = "116"; //emp.EmployeeNo = 116; // compile-time error Employee<int> emp = new Employee<int>(); emp.EmployeeNo = 116; //emp.EmployeeNo = “Hello World”; //compile-time error MultiType<int, string> multi = new MultiType<int, string>(); multi.No= 100; multi.Name= "Hundred"; MultiType< string, string> multi = new MultiType< string, string>(); multi.No= "Hundred"; multi.Name= "Hundred";
Generic Class Characteristics :
Advantage
I hope you guys, This will help you to understand the Concept of Generic in C#.
Thank you.
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular