Home > Enterprise >  Why won't the variable increase 2 times
Why won't the variable increase 2 times

Time:10-17

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

CodePudding user response:

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

CodePudding user response:

It is because num is not static, one.num and two.num are variables in different instances of Program1.

If you want to have the same num value in all instances of Program1, you can try

class Program1
{
    private static int num = 0;

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

  • Related