I wish to know whether it is possible make static field non-static and provide appropriate object to calling property. 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 static SortMethod SortOrder
{
get { return sortOrder; }
set { sortOrder = value; }
}
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 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();
}
}
Loading

VulpesPosted Oct 23, 2014, 5:11 PM
The reason it's static is because it's used in the CompareTo() method which, of course, is used to sort Person objects into some order.
If it were an instance field, then each Person object would have its own copy and could set it to a different value than other instances. Sorting could therefore potentially be a real mess with some instances sorting by firstname, others by lastname and still others by age!
By making it static you only have one copy for the whole Person class and sorting is therefore done on a consistent basis for all instances depending on the current setting.
MahaPosted Oct 23, 2014, 5:32 PM