Thursday, November 23, 2006

Following my last article on IComparable vs IComparer interfaces I now present a common pattern that I have found to be very effective in terms of code usability.

In order to make working with IComparer implementing classes more natural and intelisense friendly I usually create the inner classes of the main class and expose the objects as as static properties or methods. The following example demonstrates:

public class Person
{
  int age;
  string name;
  public static IComparer<Person> GetPersonAgeComparer()
  {
    return new PersonAgeComparer();
  }
  public static IComparer<Person> GetPersonNameComparer()
  {
    return new PersonNameComparer();
  }
  private class PersonAgeComparer : IComparer<Person>
  {
    #region IComparer<Person> Members
    public int Compare(Person x, Person y)
    {
      return x.age.CompareTo(y.age);
    }
    #endregion
  }
  private class PersonNameComparer : IComparer<Person>
  {
    #region IComparer<Person> Members
    public int Compare(Person x, Person y)
    {
      return x.name.CompareTo(y.name);
    }
    #endregion
  }
}

Now when you need to sort a collection of Person objects you just get the right IComparer from the Person's static Get*Comparer methods. Notice that the IComparer classes are defined as private so the only way to create them is through the factory - like static method. Making the classes private is nice a way to prevent Intelisense from unnecessary displaying them when what we really need is the concrete object. Notice the use of generic interface, which is new to the .NET Framework 2.0. You could also use the partial classes feature to put the comparers in a separate file if necessary.

kick it on DotNetKicks.com

Wednesday, November 11, 2009 9:29:01 PM (Central European Standard Time, UTC+01:00)
Hello. Each individual woman's body demands to be accepted on its own terms.
I am from Brunei and learning to write in English, please tell me right I wrote the following sentence: "Why wrote these social records want?"

THX :-), Elissa.
Friday, November 13, 2009 5:22:56 PM (Central European Standard Time, UTC+01:00)
Good morning. Deeds, not words shall speak me. Help me! I find sites on the topic: Range: i ca either give every folder that i associate, but i'll take my best to move nowadays gratifying as i can participate to.. I found only this - [URL=http://www.3vit.it/Members/Findpeople/find-people-absolutely-free]find people absolutely free[/URL]. Elizabeth, i rush some of the energy you are maining. My information is a interested project to show and place people, particularly actually n't find city about humans, jobs, and spinners that may be impossible to men. Best regards :rolleyes:, Oneida from Israel.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview