Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12376

ASP.NET - Giving Session object a value by its index raises error

When I write:

Session["conString"]= theConString;

It works perfectly. but if I try to write:

Session[0] = the ConString;

I get "Index was out of range. Must be non-negative and less than the size of the collection" error. I understand that this is a typical error to arrays. It means I'm trying to set value of an object that does not exist. But, how come I can do it by specifying the name for the session object. There are to ways to do so: 1Giving a string name or numeric index. I need this option because on other pages I don't want to have to memorize the string names, instead I want to declare global constants and access them using those constant names.

Upvotes: 1

Views: 255

Answers (1)

moribvndvs
moribvndvs

Reputation: 42495

The container for the session has a length of 0 when initialized, so you are trying to set the value of an element that does not exist yet. Whereas using a named key will resize the container as needed.

Upvotes: 1

Related Questions