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

Can I do an ID foreach instance of class?

I’m a newbie in c#. I am just trying to do an ID for each instance in class Person.

class Person
    {
        public Person(string name, int age)
        {
            countPersons++;
            this.name = name;
            this.age = age;
        }

        public string name { private get; set; }
        public int age { private get; set;}
        private static int countPersons { get; set; }
        
        public void GetNameAndAge()
        {
            Console.WriteLine($"Player name: {name ?? "unknown"} | Player age: {age}");
        }
        public void GetInfo()
        {
            Console.WriteLine($"Player name: {name ?? "unknown"} | Player age: {age}\nId: {countPersons}");
        }

    }

I want every class instance to have an id that starts from one (one, two, three, etc.)

class Program
    {
        public static void Main(string[] args)
        {
            var player1 = new Person("David", 31);
            var player2 = new Person("Brad", 23);
            var player3 = new Person("Michael", 26);

            player1.GetNameAndAge();
            player1.GetInfo();
            player2.GetInfo();
            player3.GetInfo();
        }
    }

But at the end of the program, the ID for everyone is 3…
(The variable countPersons is my ID)

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 :

You have to hold that in variable or property.

class Person
    {
        public Person(string name, int age)
        {
            id = countPersons++;
            this.name = name;
            this.age = age;
        }
        int id;
        public string name { private get; set; }
        public int age { private get; set;}
        private static int countPersons { get; set; }
        
        public void GetNameAndAge()
        {
            Console.WriteLine($"Player name: {name ?? "unknown"} | Player age: {age}");
        }
        public void GetInfo()
        {
            Console.WriteLine($"Player name: {name ?? "unknown"} | Player age: {age}\nId: {id}");
        }

    }

Note:

  • Static will increase with each instance creation.
  • id will hold that vlaue.
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