Do Not Panic!

If you are just starting with C# this title may scare you. Well, the terminology did scare me when I just started. However, when you look at it, those <T>’s and I’s are there to make things more easy.

What does it mean? Let’s look at that with an example.

Imagine you build a class called “Dummy”. This class has some properties, e.g. a Name, an Email and an Info (all strings). You have five dummies, and want to store them in a list.

List<T>

That is where you use a generic list. You use the build in List<T&gt, where the T means “just give me a Type, and the list will contain entries of that type only”. Your class Dummy is a Type, so you can make a List of Type Dummy. In syntax: List<Dummy>.

You add your five dumies to that list (as shown in the source code below).

The .Net framework doesn’t know anything about your dummies. Yes, it has a definition, but it does not know the exact meaning of it … in the end the .Net framework exists in a landscape of 0’s and 1’s, if you want something to happen correctly, you’ll have to tell how to do that.

System.InvalidOperationException

Imagine you want to sort your newly created list of dummies. The build-in List (the one that you made a List ) does have a sort method. If you call that method, you’ll get an System.InvalidOperationException. You told the list to sort, but you did not tell it how to do that. Sort on Name, Email, Info? And if you sort on let’s say Info, do you want it to be sorted alphabetical, or maybe some other way? The point is that the list must know how to sort. If only the Dummy class contained some infromation about that…

Interfaces: IComparable<T>

That’s where interfaces come in. If you implement an interface in a class, things like a List still don’t know anything about the meaning of your class, but they do know that there is some functionality in the class they can handle: the information provided by the interface.

When sorting, the List<T> looks for a method that tells how to sort. That method has a signature that is defined in the interface IComparable<T>.

Implementing IComparable<T> in your class means something like: This class has a method that is defined in IComparable. The type that is handled by that method is a generic, in other words, tell me the type, and I’ll respect that type when handling the method!

In our case we want that method to handle a Dummy. So what do we do? In our Dummy Class we implement the interface IComparable of type Dummy. In syntax: IComparable.

If we do so, the List knows how to sort: in your class it looks for the method that belongs to IComparable, and that method is going to tell the List how to sort.

How to sort?

How does that method tell how to sort? Well… it doesn’t by itself, you’ll have to put some code in that method for that. The method looks like this:

public int CompareTo(Dummy other)

As you can see, it returns an int, and it expects a Dummy. This is how it works. When you have an instance of Dummy, that instance also has this method. The method can be called passing another Dummy.

In your code you decide if the other Dummy should be placed before or after the current Dummy when sorting.

If the other Dummy should be placed before the current one, return 1. If the other Dummy should be placed after the current one, return -1.

This gives the List enough information to apply sorting.

Based on what do you return -1 or 1? Well, that’s up to you!

Code Example

In the following code example, a Dummy class is created, the IComparable<T> is implemented, and the sorting will be based on the number of characters in the “Info” property.

Start a new C# WPF project. Call it “Sorter”

In MainWindow.xaml replace the xaml with the following:



<Window x:Class="Sorting.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Sorting"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="17,16,0,0" VerticalAlignment="Top" Height="293" Width="490"/>
    </Grid>
</Window>

In MainWindow.xaml.cs place the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Sorting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        class Dummy : IComparable<Dummy>
        {

            public string Name { get; set; }
            public string Email { get; set; }
            public string Info { get; set; }

            public int CompareTo(Dummy other)
            {
                return (Info.Length > other.Info.Length ? -1 : 1);
             }
        }

        public MainWindow()
        {
            InitializeComponent();

            fillGrid();
        }

        void fillGrid()
        {

            List lst = new List<Dummy>();

            lst.Add(new Dummy() { Name = "Joe", Email = "joe@somedomain.com", Info = "Member of the cocker spaniel club." });
            lst.Add(new Dummy() { Name = "Adrian", Email = "adrian@somedomain.com", Info = "Used to be acrobat" });
            lst.Add(new Dummy() { Name = "Bassie", Email = "bassie@somedomain.com", Info = "His brother used to be a super-hero acrobat, now a days he sells cars." });
            lst.Add(new Dummy() { Name = "Mary", Email = "mary@somedomain.com", Info = "Sweet Mary, I'm coming home!" });
            lst.Add(new Dummy() { Name = "Roger", Email = "roger@somedomain.com", Info = "Likes swimmming in water." });

            lst.Sort();

            dataGrid.ItemsSource = lst;

        }
    }
}

Hopefully, next time you see text with a lot of <T>, capital I’s and Generics, you’ll think: Awesome, someone has spent a lot of time to make my live easier!