Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post May 05, 2012 05:32 PM by mbanavige
May 05, 2012 03:37 PM|LINK
GOT IT - STATIC DECIMAL
inside my c# code I wish to have a global variable, for instance decimal price
and when something is selected, a basic price is determined, and then with other class functions, stuff can be modified to change the price.
for instance one of 2 cars is selected, so the price can be 10k or 12k, and then tires can be upgraded, increasing the price for 500.
when i put a decimal price inside the partial class (the main container), each time a method is called this value is set to 0, so I only get the value of 0 + 500, and not 10 000 +500 or 12 000 + 500
I know this is the wrong way of doing this, and this data should be inside databases, but this is how it is supposed to be done now...
i also know that this value can be put inside a hidden label, but i dont want to do that
May 05, 2012 03:41 PM|LINK
You can set the decimal price in Application value like this in your Global.asax file
void Application_Start(object sender, EventArgs e)
// Code that runs on application startup
Application["price"] = 10;
and retive like this
int res = Convert.ToInt32(Application["price"]);
May 05, 2012 03:47 PM|LINK
are global variables the way i did it a bad practice (static decimal price)?
May 05, 2012 05:26 PM|LINK
TIMTOWTDI =. there is more than one way to do it
anything you hard code might become problematic at some future date.
ideally, you do not want to have to recompile your program for a simple change in some value.
for things that never change, such as the value of Pi (which is available via System.Math.PI as 3.14159265358979), having a
const (http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx) is an adequate solution.
for things that may change, using a .config file, a row+column in a database table, or the system registry are, imho, better solutions.
n.b.: using the system registry is somewhat challenging since Registry Virtualization (http://msdn.microsoft.com/en-us/library/windows/desktop/aa965884.aspx) was introduced
starting with Windows Vista.
May 05, 2012 05:32 PM|LINK
If your global variable is intended to be shared by all users of your site so they all see and update that one single variable, then a static does work. Most of the time though when people are asking this question, they are either looking for a method to
allow a variable to survive page postbacks (scoped to the page) or their looking for a way to preserve a value across multiple pages for a single user (scoped to a user).
Since your price variable seems to change based on user selections, i'd say that using a static would represent a bug in the code as two or more users making sleections would share just the one price variable.
Check out session or viewstate as options: