Behind the Scenes Look at C#: Indexers - C# Indexers Example (First Iteration)
(Page 2 of 4 )
Please copy the following code and compile it:
using System;
using System.Text;
namespace indexers
{
class Class1
{
static void Main(string[] args)
{
Department dept = new Department();
dept.Name = "IT";
// creating the first Employee object
Employee emp1 = new Employee();
emp1.FirstName = "Maria";
emp1.LastName = "Jack";
// creating the other employee objects
Employee emp2 = new Employee();
emp2.FirstName = "Mina";
emp2.LastName = "Jack";
Employee emp3 = new Employee();
emp3.FirstName = "Mick";
emp3.LastName = "Nelson";
Employee emp4 = new Employee();
emp4.FirstName = "John";
emp4.LastName = "smith";
Employee emp5 = new Employee();
emp5.FirstName = "Joly";
emp5.LastName = "Mac";
Employee emp6 = new Employee();
emp6.FirstName = "Steven";
emp6.LastName = "Joe";
// using the indexer
dept[0] = emp1;
dept[1] = emp2;
dept[2] = emp3;
dept[3] = emp4;
dept[4] = emp5;
dept[5] = emp6;
Console.WriteLine(dept.ToString());
Console.ReadLine();
}
}
class Department
{
private string name;
private Employee[] Employees = new Employee[6];
public Employee this[int arg]
{
get
{
return this.Employees[arg];
}
set
{
this.Employees[arg] = value;
}
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
public override string ToString()
{
StringBuilder temp = new StringBuilder();
temp.Append("The department "+this.name+" contains"+
" the following Employees\n");
foreach(Employee emp in Employees)
{
temp.Append("\n" + emp.ToString());
}
return temp.ToString();
}
}
class Employee
{
private string firstName;
private string lastName;
public string FirstName
{
get
{
return this.firstName;
}
set
{
this.firstName = value;
}
}
public string LastName
{
get
{
return this.lastName;
}
set
{
this.lastName = value;
}
}
public override string ToString()
{
return this.firstName+" "+this.lastName;
}
}
}
Run the application to get the following result to the console window:

Next: Explanation of code >>
More C# Articles
More By Michael Youssef