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.
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; }
}
                        You just need a constructor, there you can increment the count.
public Student()
{
    count++;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With