Wednesday, July 4, 2007

Programming Exercise 2: Classes - Fields, Properties and Constructors

Create a User class. This class should at least contain the following fields:
  • User ID - this is equivalent to a login name
  • Password
  • First Name
  • Last Name
  • E-mail Address
  • Status - valid values are 'Inactive', 'Active', 'Deleted'
Define constructors that accept the following parameter lists:
  • All parameters: User ID, Password, First Name, Last Name, E-mail Address
  • User ID, Password and E-mail Address
  • User ID and Password Only
** The status field should be initialized to 'Active' upon creation
** Constructors 2 and 3 should use a constructor initializer

Define read-only properties that return the following:
  • IsActive – whether or not the account's status is active
  • FullName – a concatenation of the account's first and last names
Define additional properties that behave as follows:
  • UserID
    • Set operation should ensure the user id does not start with a digit and should only update the user id field if the given value is valid
    • Get operation just returns the user id
  • Password
    • Set operation should validate the password length is within 8 to 20 characters and should only update the password field if the given value is valid
    • Get operation just returns the password
** You can reuse elements from your first programming exercise.
** Refer to the string class in the MSDN for methods in processing strings

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


class Program
{
static void Main(string[] args)
{
User user = new User("jtamad", "jtamad",
"Juan", "Tamad", "jtamad@tapulan.com");

Console.WriteLine(user.IsActive); // Outputs "True"
Console.WriteLine(user.FullName); // Outputs "Juan Tamad"

user.UserID = "1jtamad"; // Outputs an error
user.Password = "1jta"; // Outputs an error
Console.WriteLine(user.UserID); // Outputs "jtamad", no changes
Console.WriteLine(user.Password); // Outputs "jtamad", no changes

user.UserID = "juantamad";
user.Password = "juantamad";
Console.WriteLine(user.UserID); // Outputs "juantamad"
Console.WriteLine(user.Password); // Outputs "juantamad"
}
}