C# - SPLessons

C# Generic Collection

Home > Lesson > Chapter 18
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Generic Collection

C# Generic Collection

shape Description

C# Generic Collection were added to version 2.0 of the C# language and the Common Language Runtime (CLR). Generic introduced the concept of type parameters to the .NET Framework , which make it possible to design classes and methods that differ the specification of one or more types until the class or method is declared and instantiated by client code.

Using Generics

shape Description

In Constructor, specifications for the class or the method are substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.

shape Program Description

shape Example

[csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPLessons { public class Student { public Student(int id, string name) { ID = id; Name = name; } private int sid; public int ID { get { return sid; } set { sid = value; } } private string sname; public string Name { get { return sname; } set { sname = value; } } } class Program { static void Main(string[] args) { List<int> obj = new List<int>(); obj.Add(1); for (int i = 0; i < obj.Count; i++) { Console.WriteLine("Count: {0}", obj[i]); } Dictionary<int, Student> students = new Dictionary<int, Student>(); Student stu1 = new Student(1, "Shafi"); Student stu2 = new Student(2, "Shiva"); students.Add(stu1.ID, stu1); students.Add(stu2.ID, stu2); foreach (KeyValuePair<int, Student> obj1 in students) { Console.WriteLine( "ID.NO: {0}, Name: {1}", obj1.Key, obj1.Value.Name); } Console.ReadKey(); } } } [/csharp] Output: