1

So I am adding/creating objects within Console class via an array:

string[] console_available = { "Yes", "Yes", "Yes", "Yes", "Yes" };
for (int i = 0; i < console_available .Length; i++)
        {
            Classes.Console console = new Classes.Console(console_available[i]);
        }

In the class itself I have int console_id which I want to increment but for some reason it only increments it once with the below constructor:

public int ConsoleID { get; set; } = 0;
public string Available { get; set; }

public Console(string available)
    {
        ConsoleID++;
        this.Available = available;
    }

So in essence its all "1 Yes" where I need it to be "1 Yes", "2 Yes", "3 Yes".

I don't really want to go down the route of having multiple lines of code to create the objects, e.g.:

Classes.Console console  = new Classes.Console("Yes");
Classes.Console console2 = new Classes.Console("Yes");
Classes.Console console3 = new Classes.Console("Yes");
3
  • In your loop you create five objects, but throw them away, as you don´t use them anywhere. Commented Apr 9, 2020 at 14:01
  • Why not adding a second parameter (the ConsoleID) to the constructor? Commented Apr 9, 2020 at 14:03
  • ConsoleID is specific to each instance. Your constructor is adding to the variable but every time you declare a new instance, it just sets it back to 0 since that's hard coded. Make it into a static variable like @Sean answered to solve this. Commented Apr 9, 2020 at 14:04

1 Answer 1

2

You'll need a static variable that you increment and store in a member variable:

private static int _ID = 1;

public int ConsoleID { get; set; };
public string Available { get; set; }

public Console(string available)
{
    ConsoleID = _ID++;
    this.Available = available;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Simple and effective. Thank you!
Accepted now! Had to wait another 5 minutes as cannot accept an answer right after the question was posted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.