Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading