Bert Gregor
Bert Gregor

Reputation: 121

Using WebForms via C# how do I initialize/create variables that are used throughout my application?

I'm still working on my transition from traditional .asp to ASP.NET (C# Webforms). In traditional .asp I could create config.asp. Within this file, I could initialize certain variables. For example if I wanted to set a file path for uploading, downloading, etc. I could say

Dim myNameIs = "Bufford T. Jones"

Then, as long as I included the config.asp file anywhere in my app I could simply say

Response.Write myNameIs;

How do I accomplish something similar in C# Webforms? Could you please give me an example?

Upvotes: 0

Views: 374

Answers (2)

Gary Stewart
Gary Stewart

Reputation: 160

So, C# doesn't have the concept of global variables like VB.net does. In a case like this you can use session state to store information that would be available throughout the application like so:

Session["UserName"] = "Bufford T. Jones";

And then to read it:

string theUsersNameIs = (string)Session["UserName"];

Upvotes: 3

masehhat
masehhat

Reputation: 690

You can use a singleton service for manage your global properties(variables), But if you are not able to work with dependency injection, you can use static class instead of singleton service.

public static class Current
{
    public static string Username { get; set; }
}

Now you could set and get Username in throughout of your application.

Upvotes: 0

Related Questions