Introduction
Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR)
When you use generics, you are creating classes or methods that use a generic type, rather than a specific type. For example, rather than creating a type-specific, you could create a reusable List class using generics.
How is that different from the ArrayList class?
The System.Collection.ArrayList can be used with any objectn, but no type checking is done when objects are passed to methods. You have to manually cast objects back to our type when retrieving; which makes the code harder.
Using the code
I have a Strongly Typed Class named "StudentList" and Generics Class named "MyCustomList
"StudentList" class can accepts only Type of Student Objects for its Methods.
But "MyCustomList
Consider the class Student
Student dhas = new Student("Manick", "Dhas", 22);
Student raj = new Student("Sundar", "Raj", 32);
///Using a custom strongly typed StudentList
StudentList mc = new StudentList();
mc.Add(dhas);
mc.Add(raj);
Response.Write("Using a custom strongly typed StudentList
");
foreach (Student s in mc)
{
Response.Write("First Name : " + s.FirstName + "
");
Response.Write("Last Name : " + s.LastName + "
");
Response.Write("Age : " + s.Age + "
");
}
We can use MyCustomList
///Creating a list of Student objects using my custom generics
MyCustomList
student.Add(dhas);
student.Add(raj);
Response.Write("
Using a list of Student objects using my custom generics
");
foreach (Student s in student)
{
Response.Write("First Name : " + s.FirstName + "
");
Response.Write("Last Name : " + s.LastName + "
");
Response.Write("Age : " + s.Age + "
");
}
///Creating a list of Student objects using my custom generics
MyCustomList
intlist.Add(1);
intlist.Add(2);
Response.Write("
Using a list of String values using my custom generics
");
foreach (int i in intlist)
{
Response.Write("Index : " + i.ToString() + "
");
}
///Creating a list of Student objects using my custom generics
MyCustomList
strlist.Add("One");
strlist.Add("Two");
Response.Write("
Using a list of int values using my custom generics
");
foreach (string str in strlist)
{
Response.Write("Index : " + str + "
");
}
1 comment:
we're thank you for some of feature in .net 2.0
Post a Comment