C#
  Home arrow C# arrow Page 3 - Behind the Scenes Look at C#: Indexers
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Moblin 
JMSL Numerical Library 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Behind the Scenes Look at C#: Indexers
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 25
    2005-08-10

    Table of Contents:
  • Behind the Scenes Look at C#: Indexers
  • C# Indexers Example (First Iteration)
  • Explanation of code
  • A Look at the MSIL Code

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Behind the Scenes Look at C#: Indexers - Explanation of code


    (Page 3 of 4 )

    We got the expected output to the console window. The Department object contains all these instances of the Employee class, which it stores internally using the private array. Let's go through the code. We will begin with the Employee class.

    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;
      } 

    }

    There's nothing new about the Employee class. It defines two private fields (the firstName and the lastName fields) of data type string. It also defines two public properties (FirstName and LastName) to access the private fields, then it overrides the base class's method ToString() to return a representation of the Employee instance. Let's look at the Department class:

    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(); 
      }

    }

    The Department class defines a private array of type Employee that contains six elements which are used by the indexer to manipulate the objects. The Department class defines the indexer that looks much like a property, but the indexer as we have said uses the keyword "this" to refer to the current Department object. Note that the return type is an Employee instance, so in the get accessor we can return an instance of that type.

    With the indexer we don't use parentheses; we use the index operator in both the definition of the index, and when we use it. Actually we are overriding the index operator to work with our class in much the same way as it works with arrays. If you look at the get and set accessor you will not find anything new. The get accessor simply returns the object stored at the specific index of the internal array (the indexer passes the index value as an int to the internal array). The set accessor sets the object reference (using the keyword value) and sets it as the specific index in the internal array object. There is no magic involved here.

    The ToString() method of the Department class uses the class StringBuilder (that's why we have used the namespace System.Text, because this class lives in this namespace) which provides us with a dynamic string builder class. Normally if we have used the string data type it will create a new string object each time we modify the string, and refer to that new object. This can harm the performance of the application, but the class StringBuilder supports string modifications without creating a new object.

    The ToString method creates the object temp of type StringBuilder, then it uses the StringBuilder's method "append" to append a string to the object. It uses a foreach loop to iterate through all the Employee instances in the internal Employees array object. It then appends to the StringBuilder object the string that returns from a call to each Employee's ToString method. After an iteration though all the Employee instances it returns the temp.ToString() method as the string of the Department.ToString() method.

    In the Main method we simply creates six instances of type Employee, then we assign the six references to the internal array of the dept object using the indexer. We end the Main method with a call to the dept.ToString() method, which iterates through the internal array elements and returns a string representing the dept object. In this case we return all the first and last names of the employees and the name of the department. Let's take a look at the MSIL generated code for this application.

    More C# Articles
    More By Michael Youssef


     

    C# ARTICLES

    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#
    - Working with Regular Expressions in C#
    - Sending Simple E-Mail in C#
    - Building C# Comparable Objects: IComparable ...
    - Color Transformation Applications in C# GDI+...
    - Performing Color Transformation Operations i...
    - Color Transformation in C# GDI+ Programming
    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT