These are also use for providing access to the values of the class outside of the class outside of the class like a property but provides access to a value with the specific name but indexers provides access to the value with the object of a class using index positions just like an array.
We define indexers in a class as following:
Syntax:
[<modifiers>]<type> this [int index or srting name]
{
[get{<statements>}]
[set{<statements>}]
}
Indexers are defined very much similar to properties but an indexer doesn't have any name. In the place of name we use the 'this' keyword which means we are definning an indexer object of that class starts providing access to the values that are present inside the class, either with the help of index or name.
Add a class Employee.cs and write the following code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpConsole { class Employee { int _Empno; string _Ename, _Job; double _Salary; public Employee(int Empno) { this._Empno = Empno; this._Ename = "Leena"; this._Job = "Developer"; this._Salary = 5000; } public object this[int index] // accessing by 'index' { //read/wrtie properties with conditions get { if (index == 0) return _Empno; else if (index == 1) return _Ename; else if (index == 2) return _Job; else if (_Salary == 3) return _Salary; return null; } //read/write properties with conditions set { if (index == 1) _Ename = value.ToString(); else if (index == 2) _Job = value.ToString(); else if(index==3) _Salary =(Convert.ToDouble(value)); } } public object this[string name] //accessing by'name' { get { if (name == "Empno") return _Empno; else if (name == "Ename") return _Ename; else if (name == "Job") return _Job; else if (name == "Salary") return _Salary; return null; } set { if (name == "Ename") _Ename = value.ToString(); else if (name == "Job") _Job = value.ToString(); else if (name == "Salary") _Salary = Convert.ToDouble(value); } } } } Add another class TestEmployee.cs and write the following code: using System; namespace CSharpConsole { class TestEmployee { static void Main() { Employee emp = new Employee(1001); Console.WriteLine(emp[0]); Console .WriteLine (emp [1]); Console.WriteLine(emp[2]); Console.WriteLine(emp[3]); // Assigning a new value emp[1] = "Cheryl"; emp["Ename"] = "BA"; emp[3] = 8000; Console.WriteLine(emp["Empno"]); Console.WriteLine(emp["Ename"]); Console.WriteLine(emp["Job"]); Console.WriteLine(emp["Salary"]); Console.ReadLine(); } } }