Maha

Maha

  • NA
  • 600
  • 66.9k

Non-static field

Oct 23 2014 4:07 PM
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();
}
}


Answers (2)