Maha

Maha

  • NA
  • 600
  • 70.3k

Enum example

Oct 19 2014 3:29 PM
Normally to get the value inside the enum we say variable = type.value. Following example shows this. Problem is highlighted.

using System;

enum Weekday
{
Sun = 1, Mon, Tues, Wed, Thus, Fri, Sat
}
class Program
{
static void Main(string[] args)
{
Weekday wd;

wd = Weekday.Mon;

Console.WriteLine(wd);
Console.ReadKey();
}
}

But in the following example sortOrder differ from SortOrder. Please explain the reason. Problem is highlighted. One is lower case 's" other one is upper case 'S'

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.ToString());

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(); //This is not Array.Sort(people)

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

Console.ReadLine();
}
}

















Answers (7)