Introduction to Generics with example.


In this article , we will explore what is generic , its introduction , declaration of generic, how to apply this to any class and a small example of generic and its implementation. I hope it will be useful to you all. Use generic types to maximize code reuse, type safety, and performance improvement.

Generics:
Introduction:

Generics are used for type safety purpose.
It allows developers to define types as well as methods which are parameterized with type parameters.
It can be implemented as generic methods or as generic constraints.

How to declare Generic Types


class Dictionary < TKey , TValue >

How to apply it to a class :

class EmployeeList {
private T[] _classelements;
}

We can substitute TKey , TValue by other datatypes such as :

var employees = new Dictionary {
{1001 , "Suman Joshi" } ,
{1002 , "Leena Kulkarni" } ,
{1003 , "kamala Shinde"} ,
{1004 , "Vimala Shirole"} ,
{1005 , "Kavita Sarode"}
};

Description:

Generic Contract can also be defined.
Generic can also be applied to interface.
Collection classes can be created using generic concept. It was introduced in version 2.0 and CLR.
This way you can have your own generic methods, interfaces, classes, events and delegates.
System.Collections namespace is used for generic implementation.

Consider following class

namespace School {
public class student {
protected string student_name;
protected int student_rollno;
public string student_Name
{
get{return student_name;
}
set{student_name=value;
}
}
public int student_RollNo
{
get
{
return student_rollno;}
set
{
student_rollno=value;
}
}
}
}

Generic version:

System.Collections.Generic.List School_Students
= new System.Collections.Generic.List();


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: