Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET C# globally available object

How would I add a Stack object into my global.asax so it's accessible by the entire application? At the moment I have:

void Application_Start(object sender, EventArgs e)
{
    // Global vars
    Application.Add("ArcadeTotalUniquePlayers", 0);
    Application.Add("ArcadeTotalPlays", 0);
    Stack<int> ArcadeLastPlayers = new Stack<int>(16);

The first two variables work, but I'm not sure how to make the Stack globally accessible.

like image 758
Tom Gullen Avatar asked Feb 22 '23 21:02

Tom Gullen


2 Answers

You could do:

Application.Add("ArcadeLastPlayers", new Stack<int>());

and then

((Stack<int>)Application["ArcadeLastPlayers"]).Pop();

Or you could make some sort of global static, so you don't have to cast it every time you need to retrieve it:

namespace GlobalUtils {
    public static class ArcadeData {
        public static Stack<int> ArcadeLastPlayers = new Stack<int>();
    }
}

and then

GlobalUtils.ArcadeData.ArcadeLastPlayers.Pop();
like image 170
Adam Rackis Avatar answered Mar 04 '23 11:03

Adam Rackis


If you want use the HttpApplcationState, you should be able to just do the following:

Application.Add("ArcadeLastPlayers", new Stack<int>(16));

HttpApplicationState takes a string for the name and an object as the associated value. All you would have to do is cast it to a Stack when you retrieve the "ArcadeLastPlayers" value.

like image 22
Nadir Muzaffar Avatar answered Mar 04 '23 10:03

Nadir Muzaffar