Change
static int generateId()
{
int id = 1; //This resets the value to 1 every time you enter.
return id+= 1;
}
To:
private static int id = 1;
static int generateId()
{
return id++;
}
Your generateId will always return 2 since you're passing out a local value that you initialize to 1 each time it's entered. With my example, Id will be set to 1 when the app is run and then increments. It will always start at 1, though.
Adding explanation of local variables, field variables, and static variables.
When you define a variable like you did, a local variable, it only exists within the scope of the method and will get reinitialized each time the method is called.
You can also define field variables that will exist as long as an instance of an object exists. For example:
public class AutoIncrment
{
private int id = 1;
public int GenerateId()
{
return id++;
}
}
You can use it like this:
var idState = new AutoIncrement();
console.WriteLine(idState.GenerateId()); // Outputs 1
console.WriteLine(idState.GenerateId()); // Outputs 2
console.WriteLine(idState.GenerateId()); // Outputs 3
console.WriteLine(idState.GenerateId()); // Outputs 4 .. And so on
var idState2 = new AutoIncrement(); // Create a new instance and it starts over
console.WriteLine(idState2.GenerateId()); // Outputs 1
console.WriteLine(idState2.GenerateId()); // Outputs 2 .. And so on
// Go back to idState object and it will keep going from where you last left off
console.WriteLine(idState.GenerateId()); // Outputs 5
Then there are static variables like in my answer at the top. They exist as part of the class itself. Since the class always exists while the program is running, the variable exists in memory, too.