I have created a Dictionary in Application scope, but I’m not sure how to correctly access it in another page.
void Application_Start(object sender, EventArgs e)
{
Application["PaginationTable"] = new Dictionary<int, int>();
Dictionary<int, int> dictPagination = new Dictionary<int, int>();
//fill dict
for (int i = 0; i < 40; i++)
{
etc
}
Application["PaginationTable"] = dictPagination;
}
In myotherpage.cs
foreach (KeyValuePair<int, int> pair in Application["PaginationTable"])
{
Response.Write(pair.Key +" :: " + pair.Value + "<br>");
etc
}
The error generated is:
“foreach statement cannot operate on variables of type ‘object’ because ‘object’ does not contain a public definition for ‘GetEnumerator'”
The gist is that I need to create a Dictionary to hold a table of value/pair data that will not change and will need accessing/compared by different sections of the website.
Help appreciated
As
Applicationcan store many different types, it has to store them asObject, the parent class all types are inherited from. You need to cast theApplication["PaginationTable"]to the correct type, i.e.Dictionary<int, int>that foreach can operate on. i.e.:Note that to save typing
KeyValuePair<int, int>can be replaced withvar, as the compiler can work out the correct type at compile time.Also note that the line
is redundant as you just assign another object to it lower down.