Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How count number of objects created with a static class variable?

Tags:

c#

I created 3 objects of a class and I want to display on the console how many objects I have created (using a static class variable) - How do I do this ?

I put public static int count = 0; in the class I created but I couldn't get it to increment (count++;) based on how many objects I created of the class. I created the 3 objects in the main method and gave them values for variables.

here is the class I created in my program :

public class Student
        {

           public static int count = 0;
       //     count++;


            private string firstName;

            public string FirstName

            {           
                get { return firstName; }
                set { firstName = value; }
            }


            private string lastName;

            public string LastName
            {
                get { return lastName; }
                set { lastName = value; }
            }
            private string birthDate;

            public string BirthDate
            {
                get { return birthDate; }
                set { birthDate = value; }
            }
        }

In the main method I created 3 objects of class Student:

static void Main(string[] args)
        {

         //  Create 3 students    
            Student student1 = new Student       
            {
                FirstName = "John",
                LastName = "Wayne",
                BirthDate = "26/05/1907"

            };

            Student student2 = new Student
            {
                FirstName = "Craig",
                LastName = "Playstead",
                BirthDate ="01/01/1967"
            };

            Student student3 = new Student
            {
                FirstName = "Paula",
                LastName = "Smith",
                BirthDate = "01/12/1977"
            };


            // Console.WriteLine("The course contains {1} students(s) " studentCounter );

I can't get the counter to ++ based on the way I created the objects.

like image 757
Aindriú Avatar asked Dec 08 '22 03:12

Aindriú


2 Answers

Increment the count in the constructor:

public class Student
{
    public static int count = 0;
    public Student()
    {
        // Thread safe since this is a static property
        Interlocked.Increment(ref count);
    }

    // use properties!
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string BirthDate { get; set; }
}
like image 127
Amir Popovich Avatar answered May 04 '23 16:05

Amir Popovich


You just need a constructor, there you can increment the count.

public Student()
{
    count++;
}
like image 38
Franky Avatar answered May 04 '23 18:05

Franky