Why won't the variable increase 2 times

I wrote a class and 2 new constructors, but the num increases its value only 1 time and I don’t know why.

using System;

Program1 one = new Program1("name1");
Program1 two = new Program1("name2");

class Program1
{
    private int num = 0;

    public Program1(string name)
    {
        num++;
        Console.WriteLine($"It is your {num} object");
        Console.WriteLine($"{name} is your object");
    }
}

Console:

It is your 1 object
name1 is your object
It is your 1 object
name2 is your object

>Solution :

Currently, num is an instance member of the class. So, each time you create a new instance, num is a different field with its own value.

If you want its value to increase regardless of the instance, you can turn it into a static field or property:

private static int num = 0;

Now, each time you call new Program1(someString), the value of num will increase.

Be aware that in this case, each instance will not have its own value of num. To test this, let’s add the following method to the class

public void PrintNum()
{
    Console.WriteLine(num);
}

Now, the following code:

Program1 one = new Program1("name1");
Program1 two = new Program1("name2");

Console.Write("one.PrintNum: "); one.PrintNum();
Console.Write("two.PrintNum: "); two.PrintNum();

…will produce:

It is your 1 object
name1 is your object
It is your 2 object
name2 is your object
one.PrintNum: 2
two.PrintNum: 2

Leave a Reply