Part 64 – C# Tutorial – How And Where Are Indexers Used In .net


Tags
c# indexer advantages
why we use indexers in c#
use of indexer in c#
what are indexers in c#

The HTML and the code used in the demo, can be found at the link below.

Link for csharp, asp.net, ado.net, dotnet basics and sql server video tutorial playlists

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 = “Session 1 Data”;
// Using the string indexer to store session data
Session = “Session 2 Data”;

// Using the integral indexer to retrieve data
Response.Write(“Session 1 Data = ” + Session.ToString());
// Using the string indexer to retrieve data
Response.Write(“Session 2 Data = ” + Session.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.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.ToString() + ” “);
// Using string indexer to retrieve Id column value
Response.Write(“Name = ” + rdr.ToString());
}
}

Right click on SqlDataReader class, 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.


You may also like...