Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to change value of variable Year from 2019 to 2020 permanently as show below line

private static int Year = 2019;


but i am enable to change it.
I use asp.net mvc and change code line from controller is given below

FirstProject.Models.MyClass.setYear(2020);


What I have tried:

public static class MyClass
    {
        private static int Year = 2019;
        public static void setYear(int year)
        {
            Year = year;
        }
        public static int getYear()
        {
            return Year;
        }

}
Posted
Updated 18-Nov-19 22:28pm

Your code changes the value of the Year "permanently" for teh application - it will not revert to 2019 while the app is running.

But ... if you want the value to change and that value to be persisted in the app next time you run it you need to save the new value somewhere, and load it next time your app runs.

There are many types of places your could save it, but ... there are problems here. MVC is web based, which means that multiple people could be using it at the same time, and due to the way web servers work, that means that static variables can't be trusted as the app is "shared" between clients until it's unloaded - and the static variable is also "shared".

For a web based app, I'd store Year in a DB, update it in the DB, and reload it when the app tries to use it. That way, it's correctly shared between clients and they will all get the "new value" immediately after it changes.
 
Share this answer
 
Comments
CPallini 19-Nov-19 3:59am    
5.
If you just want to know what the current year is :)

C#
public static class MyClass
{
    public static int getYear()
    {
        return DateTime.Now.Year;
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900