Monday, July 9, 2007

Programming Exercise 3: Classes - Static Fields and Static Constructors

Define additional fields in your existing User class.
  • _dateCreated (static readonly) - Date of object creation
  • ClassesCreated (static) - Number of objects instantiated
Define a static constructor that initializes the ClassesCreated field to 0.

Modify your existing constructor to set values for the additional fields:
  • The _dateCreated field is set to the current date
  • The ClassesCreated field is incremented
Define a read-only property for the _dateCreated field

After implementing these, you should be able to use your class as follows:


class Program
{
static void Main(string[] args)
{
User user1 = new User("user1", "password1");
Console.WriteLine(user1.DateCreated); // Outputs the creation date for user1
Console.WriteLine(User.ClassesCreated); // Outputs "1" since this is the first object

User user2 = new User("user2", "password2");
Console.WriteLine(user2.DateCreated); // Outputs the creation date for user2
Console.WriteLine(User.ClassesCreated); // Outputs "2" since this is the second object
Console.ReadLine();
}
}