Wednesday, July 11, 2007

Programming Exercise 4: Classes - Methods

Define a Deactivate() method in your existing User class. Calling this method will set its status field to Inactive.

This is the expected output when using your class:


class Program
{
static void Main(string[] args)
{
User user = new User("jtamad", "jtamad");
Console.WriteLine(user.IsActive); // Outputs "True" (default value)
user.Deactivate();
Console.WriteLine(user.IsActive); // Outputs "False"
Console.ReadLine();
}
}


Define another method, GetCopy(), that allows the class to return a copy of itself. Hint: Use the MemberwiseClone() method inherited from System.Object. You also need to perform a cast to the appropriate User object as this method returns a System.Object type.

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


class Program
{
static void Main(string[] args)
{
User user1 = new User("jtamad", "jtamad");
Console.WriteLine(user1.UserID); // Outputs "jtamad"

User user2 = user1; // user2 references the
// same object as user1
user2.UserID = "juantamad"; // Modifies user1 also
// since user2 references
// the same object as user1
Console.WriteLine(user1.UserID); // Outputs "juantamad

user2 = user1.GetCopy(); // user2 has its own copy
// of a User object copied
// from user1
user2.UserID = "jtamad"; // Does not affect user1
// since this is a new object
Console.WriteLine(user1.UserID); // Outputs "juantamad"
Console.WriteLine(user2.UserID); // Outputs "jtamad"

Console.ReadLine();
}
}