Maha

Maha

  • NA
  • 600
  • 70.6k

Enum example

Oct 18 2014 9:11 AM
When I use Step Into (F11) key in the first round of execution, execution bar is straight way jump into return firstname.CompareTo(p2.Firstname); from the switch (sortOrder) code. Even though there is no indication to the compiler to do so. I wish to know the reason for that.

In the 2nd round of execution compiler is directed by the code Person.SortOrder = Person.SortMethod.Lastname; what should be done in the switch statement. I can understand this.

Problem is highlighted.

using System;
using System.Collections;

public class Person : IComparable
{
public enum SortMethod
{ Firstname = 0, Lastname = 1, Age = 2 };

private string firstname;
private string lastname;
private int age;
private static SortMethod sortOrder;

public string Firstname
{
get { return firstname; }
set { firstname = value; }
}

public string Lastname
{
get { return lastname; }
set { lastname = value; }
}

public int Age
{
get { return age; }
set { age = value; }
}

public static SortMethod SortOrder
{
get { return sortOrder; }
set { sortOrder = value; }
}

public Person(string firstname, string lastname, int age)
{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}

public override string ToString()
{
return String.Format("{0} {1}, Age = {2}", firstname, lastname, age.ToString());
}

public int CompareTo(object obj)
{
if (obj is Person)
{
Person p2 = (Person)obj;

switch (sortOrder)
{
case SortMethod.Lastname:
return lastname.CompareTo(p2.Lastname);
case SortMethod.Age:
return age.CompareTo(p2.Age);
case SortMethod.Firstname:
default:
return firstname.CompareTo(p2.Firstname);
}
}
else
throw new ArgumentException("Object is not a Person.");
}
}

public class TestClass
{
public static void Main()
{
ArrayList people = new ArrayList();
people.Add(new Person("John", "Doe", 76));
people.Add(new Person("Abby", "Normal", 25));
people.Add(new Person("Jane", "Doe", 84));

people.Sort();

foreach (Person p in people)
Console.WriteLine(p);

Console.ReadLine();

Person.SortOrder = Person.SortMethod.Lastname;

people.Sort();

foreach (Person p in people)
Console.WriteLine(p);

Console.ReadLine();

Person.SortOrder = Person.SortMethod.Age;

people.Sort(); //not Array.Sort(people)

foreach (Person p in people)
Console.WriteLine(p);

Console.ReadLine();
}
}


Answers (2)