C# Generic Collections Part 3: User defined types

In case of generic collection the types of value we want to store under the collections need not be pre-defined types like int,float,double,string etc... But it can also be some user defined types.

Code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace genericUserDefined  
  8. {  
  9.     class Employee  
  10.     {  
  11.         public int eid { get; set; }  
  12.         public string first_name { get; set; }  
  13.         public string last_name { get; set; }  
  14.         public string department { get; set; }  
  15.         public double salary { get; set; }  
  16.     }  
  17. }  
  18.   
  19.   
  20. //Main class  
  21.   
  22. using System;  
  23. using System.Collections.Generic;  
  24. using System.Linq;  
  25. using System.Text;  
  26. using System.Threading.Tasks;  
  27.   
  28. namespace genericUserDefined  
  29. {  
  30.     class Program  
  31.     {  
  32.         static void Main(string[] args)  
  33.         {  
  34.             List<Employee> elist = new List<Employee>();//Declare user defined type employee in the list  
  35.   
  36.             Employee e1 = new Employee();  
  37.             e1.eid = 101;  
  38.             e1.first_name = "Sujan";  
  39.             e1.last_name = "Hasan";  
  40.             e1.department = "IT";  
  41.             e1.salary = 55000.00;  
  42.   
  43.             elist.Add(e1);  
  44.   
  45.             Employee e2 = new Employee();  
  46.             e2.eid = 102;  
  47.             e2.first_name = "Shakil";  
  48.             e2.last_name = "Sorker";  
  49.             e2.department = "Networking";  
  50.             e2.salary = 75000.00;  
  51.   
  52.             elist.Add(e2);  
  53.   
  54.             Employee e3 = new Employee();  
  55.             e3.eid = 100;  
  56.             e3.first_name = "Shimul";  
  57.             e3.last_name = "Hossain";  
  58.             e3.department = "CEO";  
  59.             e3.salary = 175000.50;  
  60.             elist.Add(e3);  
  61.   
  62.             print(elist);  
  63.             Console.ReadKey();  
  64.         }  
  65.         public static void print(List<Employee> emp)  
  66.         {  
  67.             foreach (Employee obj in emp)  
  68.             {  
  69.                 Console.WriteLine(obj.eid+" "+obj.first_name+" "+obj.last_name+" "+obj.department+" "+obj.salary);  
  70.             }  
  71.         }  
  72.     }  
  73. }  
Share:

0 Comments:

Post a Comment