Thursday, November 12, 2015

Indexer

An Indexer is a public property of a class that is used to fetch values from a collection contained by class in an efficient & easy way.
Indexer makes a class as a virtual array.
  1. this keyword is used to create indexer
  2. Indexer can be overloaded
  3. More then one parameters can be used for indexing

Source Code:
public class Student
{
    public int RollNo { get; set; }
    public string Name { get; set; }
    public string Class { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        school objSchool = new school();
        
        //Class object used as an array using Indexer
        Student obj1 = objSchool[2];    //Indexer1  
        Student obj2 = objSchool["Ravi"]; //Indexer2
        
        Console.WriteLine("Student Roll No:{0}, Name:{1}",obj1.RollNo, obj1.Name);
        Console.WriteLine("Student Roll No:{0}, Name:{1}", obj2.RollNo, obj2.Name);
        Console.ReadLine();
    }

    class school
    {
        private List<Student> lstStudent = new List<Student>();
        public school()
        {
            lstStudent.Add(new Student { RollNo = 1, Name = "Ram", Class = "5th" });
            lstStudent.Add(new Student { RollNo = 2, Name = "Shiv", Class = "6th" });
            lstStudent.Add(new Student { RollNo = 3, Name = "Ravi", Class = "5th" });
        }
      
        public Student this[int rollNo]  //Indexer
        {
            get
            {
                return lstStudent.Find(new Predicate<Student>(x => x.RollNo == rollNo));
            }
            set
            {
              //lstStudent.Find(new Predicate<Student>(x => x.RollNo == rollNo)).RollNo = rollNo; //Set can be used but here it does not have meaning
            }
        }
        public Student this[string name] //overloading of indexer
        {
            get
            {
                return lstStudent.Find(new Predicate<Student>(x => x.Name == name));
            }
            set
            {
             //lstStudent.Find(new Predicate<Student>(x => x.Name == name)).Name = name;
            }
        }
    }
}

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...