February 24, 2011

Generics example in C#

Create 4 student objects with attributes Id,Name .
Add those in Generic List.


//Below is the code


using System;

using System.Collections.Generic;
class Student
{
   int s_Id;
   public int STUDENTID
   {
        get { return s_Id; }


        set { s_Id = value; }
   }


   string S_Name;
   public string STUDENTNAME 
   {
       get { return S_Name; }


       set { S_Name = value; }
   }
       
    public Student(int SID, string SNAME)
   {
     this.s_Id=SID;
     this.S_Name=SNAME ;


   }


}


// Main class as follows:

class Program
{
  static void Main(string[] args)
  {
    // add student objects in generic List
    List<Student > StudentList = new List<Student>();


    StudentList.Add(new Student (1,"test1"));
    StudentList.Add(new Student(2, "test2"));
    StudentList.Add(new Student(3, "test3"));
    StudentList.Add(new Student(4, "test4"));


    //traverse through the list
    foreach (Student s in StudentList)
    {
      Console.WriteLine("Studnet Id");
      Console.WriteLine(s.STUDENTID);


      Console.WriteLine("Studnet Name");
      Console.WriteLine(s.STUDENTNAME);
      Console.WriteLine("");
      Console.WriteLine("");
      Console.WriteLine("");
    }
    Console.ReadLine();
  }
}


Below is the o/p

No comments:

Post a Comment