Indexers :

Indexers : 

They are similar to properties .For ASP .net Web application , We have the concept of session state and application state variables.To retireve the session state and application state variables we use indexers .Indexers allow instance of classes to be indexed just like arrays.
public string this[int id]
        {
            get
            {

            }

            set
            {
            }
        }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace ManualResetEvent_
{
    //Company class and Employee classs

    class Employee
    {
        public int EmployeeId { get; set; }
        public string  EmployeeName { get; set; }
        public int EmployeeSalary { get; set; }
    }


    //This will contain list of employees
    class Company
    {
        private List<Employee> listEmployee;

        public Company()
        {
            listEmployee = new List<Employee>();
            listEmployee.Add(new Employee(){EmployeeId=1,EmployeeName="XXX",EmployeeSalary=1000});
            listEmployee.Add(new Employee(){EmployeeId=2,EmployeeName="YYY",EmployeeSalary=2000});
            listEmployee.Add(new Employee(){EmployeeId=3,EmployeeName="ZZZ",EmployeeSalary=3000});
        }

        public string this[int id]
        {
            get
            {
                Console.WriteLine("get is being called");
                return listEmployee.FirstOrDefault(emp => emp.EmployeeId == id).EmployeeName;

            }

            set
            {
                Console.WriteLine(" Set is being called");
                listEmployee.FirstOrDefault(emp => emp.EmployeeId == id).EmployeeName = value;
            }
        }
    }

    class prog
    {
        public static void Main()
        {
            Company cmp = new Company();
            Console.WriteLine(" The Name of the employee with Id 3 is {0}",cmp[3]);
            Console.WriteLine(" The Name of the employee with Id 1 is {0}",cmp[1]);
            Console.WriteLine(" The Name of the employee with Id 2 is {0}",cmp[2]);

            cmp[2] = "MMM";
            Console.WriteLine(" The Name of the employee with Id 2 is {0}",cmp[2]);
            Console.ReadLine();

        }
    }


Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6