Popular Posts

Nov 16, 2012

Generics- C#




- Generics are used to help make the code in the software components much more
reusable.
- They are a type of data structure that contains code that remains the same. 
- The data type of the parameters can change with each use.
- The usage within the data structure adapts to the different data type of the passed
variables. 


Create a console project then create a class Person.
public class Person
    {
       private string _Name;
       private int _Age;
      

      
      public string Name
       {
          get{return _Name;}
          set{_Name = value;}
       }

       public int Age
       {
          get{return _Age;}
          set{_Age = value;}
       }

    }



In Programs.cs file write the code:
System.Collections.Generic.List employees = new System.Collections.Generic.List();


// now add a couple of generic person objects to the generic collection 
             Person p1 = new Person();
             p1.Name = "John";
             p1.Age = 23;
             employees.Add(p1);

             Person p2 = new Person();
             p2.Name = "James";
             p2.Age = 34;
             employees.Add(p2);

            // now we have a type-safe collection of objects with the 
            // richness of Intellisense built in 
            // print out the contents of the collection 
            foreach (Person p in employees) 
            { 
               Console.WriteLine(String.Format("{0} - {1}", p.Name, p.Age)); 
            }

            Console.ReadKey();







No comments:

Post a Comment