HI WELCOME TO SIRIS

C# Tutorial - How and where are indexers used in .net

Leave a Comment
Where are indexers used in .NET
To store or retrieve data from session state or application state variables, we use indexers.
// 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());

If you view the metadata of HttpSessionState class, you can see that there is an integral and string indexer defined. We use "this" keyword to create indexers in c#. We will discuss about creating indexers in our next video session.


Another example of indexers usage in .NET. To retrieve data from a specific column when looping thru "SqlDataReader" object, we can use either the integral indexer or string indexer.
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
    SqlCommand cmd = new SqlCommand("Select * from tblEmployee", con);
    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        // Using integral indexer to retrieve Id column value
        Response.Write("Id = " + rdr[0].ToString() + " ");
        // Using string indexer to retrieve Id column value
        Response.Write("Name = " + rdr["Name"].ToString());
        Response.Write("<br/>");
    }
}

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


What are indexers in c#?
From the above examples, it should be clear that, Indexers allow instances of a class to be indexed just like arrays.

In our next video, we will discuss about creating indexers.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.