Friday, 2 March 2012

How to Use Custom Types with Generic Collections?

Yes, we can we existing List<T>[List is a collection] also we can use with custom types like student,person,employee............ect

Ex:

 public class Student
    {
           private string _Name;
           private int _Age;
           public string Name
           {
              get{return _Name;}
              set{_Name = value;}
           }

           public int Age
           {
              get{return _Age;}
              set{_Age = value;}
           }
        }
this is my custom type is called Student. Now i want to perpare a collection like premetive types.yes we can prepares studentscollection here is Stulist



     static void Main(string[] args)
        {          
            List<Student> Stulist = new List<Student>();
            Student P1 = new Student();
            P1.Age = 25;
            P1.Name = "anand";
            Stulist.Add(P1);        
            Student P2 = new Student();
            P2.Age = 26;
            P2.Name = "balu";
            Stulist.Add(P2);
            IEnumerator<Student> ierStudent = Stulist.GetEnumerator();
            while (ierStudent.MoveNext())
            {
                Student p = ierStudent.Current;
                Console.Write("Student name : "+p.Name + "   Age :  " + p.Age+"\n");              
            }
            Console.ReadKey();
        }
Now we have to keep in mind one point is

NOTE:
   Class List<T>:IEnumerable<T>
{
}
We no need to implement IEnmerable interface by the Person type. why because List<T> collection[generic class]  implements  IEnumerable<T> interface. But If we  use our own collection like may be studentscollection then it has to implement the IEnumerable interface to iterate through the members.


No comments:

Post a Comment