Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

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

Suggested Videos 
Part 61 - Partial classes
Part 62 - Creating partial classes
Part 63 - Partial methods



In this video we will discuss about
1. Where are indexers used in .NET
2. What are indexers in c#



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.

1 comment:

  1. Before these videos , programming was very hard to learn for me. These videos makes it easy and now programming is very simple task for me.

    ReplyDelete

It would be great if you can help share these free resources