0

I'm not sure if this question has been asked before but here I go.

class Program
{

    protected int ID;

    static void Main(string[] args)
    {
        var Obj = new Program();
        Obj.Inc();
        Console.WriteLine(Obj.ID);
        Console.ReadLine();
    }

    public int Inc()
    {
        return ++ID;
    }

}

output: 1

The problem is this, when I run it again, shouldn't my output be 2, but I keep getting 1 every time I run the program.

invidicult
  • 306
  • 2
  • 8
  • 19
  • That's because, each time you re-run the program, the `ID` attribute of the `Program` class is re-initialised to 0. The value of `ID` is not stored somewhere in between each of the times you run the program. – Re Captcha May 28 '15 at 09:46
  • ok, thanks, so how do I store the value of ID somewhere, so when I re-run the program again I get a different value for ID. – Mishael Ogochukwu May 28 '15 at 09:55

2 Answers2

1

Yes you will get output 1 every time you run the program again. When you re-run program, everything will get reinitialized. So you need to store it in database to get it back in future.

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
1

When your application restarts, it doesn't remember variables from the previous run.

If you want that, you need to persist their values and read them upon startup. There are many, many ways to do that.

You can use configuration files, settings files, text files in any format, serialized classes, perhaps even a database. Just search the web or this site for "C# persist variables".

See Storing settings/variables persistantly in C#/.NET, How to save variable values on program exit?, and so on.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272