What Are Indexers in C#

Where Are Indexers used in .Net?

Indexers are used in .Net to store or retrieve data from a session state or application state variables.

If you are an ASP.Net application developer then you must be familiar with session state variables and application state variables. To store or retrieve data from application state or session state variables, we use Indexers.

Example:

// Using the string indexer to store session data
Session["Session1"] = "Session 1 Data";
// Using the string indexer to store session data
Session["Session2"] = "Session 2 Data";

// Using the integral indexer to retrieve data
Response.Write("Session 1 Data = " + Session[0].ToString());
Response.Write("<br/>");
// Using the string indexer to retrieve data
Response.Write("Session 2 Data = " + Session["Session2"].ToString());

Explanation of the preceding example:

I created a simple ASP.Net web application project with one webform, within the code behind file in the page_Load event let's say I want to store something into session state variables. Then I can make use a session object.

The moment we open the square bracket(session[....) we can see that there are two Indexers defined on the session object, the first Index here is "Integral Indexer" and once we press the down arrow we can see that there is another Indexer and this is a "string Indexer". The fact that we have two indexers for this session object indicates that it is possible to overload Indexers.

Step 1

Let's say I want to store something into this session object and let's say I want to use the string Indexer as in the following:

session["session1"] =

Now I want to store "session1 data" into this session object with that key.

session["session1"] = "session1 data";

Step 2

I want to store another string. Let's call the "Session 2 data" and this time the key is going to session2.

Here, we are using the Indexer to actually store the data into the session object. It is possible to retrieve data using "Indexers".

Step 3

I need to use Response.Write(). Now let's print the "session1 data = " and I am going to use a session object (session[ ). It shows again that I have "Integral Indexer" and "String Indexer".

And I actually use an Integral Indexer to retrieve the data out of the first session key.

So I will "0" as the Indexer, so the "0" Index will pull the data that is present in the first session key. The session object is the actual object data type returned because you can store anything into a session state.

We know that it is a string so I am going to convert that to a string (.Tostring();).

Now let's write a HTML break output so it comes on a seperate line..

Step 4


Now I want use a string Indexer to specify our session key.

Response.Write("session2 data = " + session["session2"].Tostring());

Finally, if you view the metadata of the HttpSessionState class, you can see that there is an integral and string indexer defined. We use the "this" keyword to create indexers in C#.

Note: Right-click on the Session and "Go to definition"; you see the session property.

public virtual HttpSessionState Session { get; }

This is actually returning a HttpSessionState object , so right-click on the HttpSessionState object then "Go to Definition".

Within that class you should see two Indexers, Integral Indexer and String Indexer.

public sealed class HttpSessionState : ICollection, IEnumerable
    {
       
        public int CodePage { get; set;}
        public HttpSessionState Contents { get; }
        public HttpCookieMode CookieMode { get; }
        public int Count { get; }
        public bool IsCookieless { get; }
        public bool IsNewSession { get; }
        public bool IsReadOnly { get; }
        public bool IsSynchronized { get; }
        public NameObjectCollectionBase.KeysCollection Keys { get; }
        public int LCID { get; set; }
        public SessionStateMode Mode { get; }
        public string SessionID { get; }
        public HttpStaticObjectsCollection StaticObjects { get; }
        public object SyncRoot { get; }
        public int Timeout { get; set; }

        public object this[int index] { get; set; }
        public object this[string name] { get; set; }


We should create Indexers using the "this" keyword.

Another example of Indexers usage in .Net is to retrieve data from data of a specific column when looping through a "SqlDatareader" object, we can use either "Integral Indexer " or "String Indexer".

Example:

First I created a table in Database(select * from Employee) , I want retrieve data from the table and write that on a webform.

Obviously we need to write some ADO.Net code.

In the web.config file: in the web.config file I already have a connection string
as in the following:

<configuration>
  <
connectionStrings>
    <
add name="DBCS"
         connectionString="data source=Eskilla-PC;Database=SPROC; Integrated Security=SSPI"
         providerName="System.Data.SqlClient" /></connectionStrings>
public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        string cs= ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("select * from Employee", con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
 
                while (rdr.Read())
                {
                    Response.Write("Id = " + rdr[0].ToString() + "");
                    Response.Write("Name = " +rdr["Name"].ToString());
                    Response.Write("<br/>");

                }
            }
        }
    }
}


Right-click on the SqlDataReader class and select "Go To Definition", to view it's metadata there is an integral and string indexer defined.

public class SqlDataReader : DbDataReader, IDataReader, IDisposable, IDataRecord
    {
        protected SqlConnection Connection { get; }
        public override int Depth { get; }
        public override int FieldCount { get; }
        public override bool HasRows { get; }
        public override bool IsClosed { get; }
        public override int RecordsAffected { get; }
        public override int VisibleFieldCount { get; }

        public override object this[int i] { get; }
        public override object this[string name] { get; }


What Indexers are in C#

It should be clear that, Indexers allow instances of a class to be indexed just like arrays.


Similar Articles