C# Delegates Real World Usage

asp.netcnet

I've previously asked a question of about Delegates does anyone have a must have scenario where I would have to use a delegate? How does this improve my C# code?

Just as many scenarios I use it in I've always seem to be able to program around it.

Best Answer

Assuming you're not talking about events - of course you can program around it. The point is to make it nicer and cleaner.

protected void Sort()
{
    foreach (string key in _dBase.Keys)
    {
      Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], 
            new Comparison<Pair<string, Dictionary<string, T>>>(
        delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b)
        {
            if (a == null && b != null)
                return 1;
            else if (a != null && b == null)
                return -1;
            else if (a == null && b == null)
                return 0;
            else
                return a.First.CompareTo(b.First);
        }));
    }
}

Could I do that without an inline delegate? Sure. Would I have a floppy private method in my class that would only be used for this one instance? Yup.

Edit: As mentioned in the comments, you can simplify:

Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], 
   new Comparison<Pair<string, Dictionary<string, T>>>(
   delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b)
   {

to

Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], (a,b) =>
   {