DCSIMG
July 2010 - Posts - Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

July 2010 - Posts

How to be a Cool C# Programmer

Published at Jul 20 2010, 10:35 PM by pavely

There are many C# programmers out there… but you probably want to be the coolest… it’s not enough to just call a bunch of methods, invoke some delegates, etc. You need to write it cool.

Here are some ways you can make yourself a cool C# programmer (and pick up geeky chicks at your local C# party):

1. Use anonymous delegates whenever possible (or lambda expressions, see 2):

var nums = new List<int>();

//...

var nums2 = nums.FindAll(delegate(int n) {

   return n % 2 == 0;

});

 

2. Use lambda expressions when delegates are required (this is super-cool):

button1.Click += (s, e) => {

   MessageBox.Show("This is super-cool!");

};

 

3. If you’re using a lambda expression that accepts one argument and you don’t need it, provide its name as underscore:

ThreadPool.QueueUserWorkItem((_) => {

   Console.WriteLine("This is way too cool!");

});

 

4. When raising events, the event should be checked to be non-null, but the cool thing to do is always register an empty handler so the check is unnecessary:

class Printer {

   public event EventHandler PagePrinted = delegate { };

   //...

   protected virtual void OnPagePrinted() {

      PagePrinted(this, EventArgs.Empty); // look ma, no check!

   }

}

 

5. Use LINQ whenever possible, using complex operators if you can:

var procs = from p in Process.GetProcesses()

            where p.Threads.Count > 15

            orderby p.ProcessName

            group new {

               Name = p.ProcessName,

               Id = p.Id,

               Threads = p.Threads.Count

            } by p.BasePriority into g

            orderby g.Key descending

            select g;

 

foreach(var g in procs) {

   Console.WriteLine("Priority {0}", g.Key);

   foreach(var p in g)

      Console.WriteLine("  {0}", p);

}

 

6. Use LINQ some more:

static class ObjectExtensions {

   public static void CopyFrom(this object target, object src) {

      var props = from p1 in src.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)

                  from p2 in target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)

                  where p1.PropertyType == p2.PropertyType && p1.Name == p2.Name && p1.CanRead && p2.CanWrite

                  select new {

                     Src = p1,

                     Dst = p2

                  };

      foreach(var p in props)

         p.Dst.SetValue(target, p.Src.GetValue(src, null), null);

   }

}

 

7. Use yield to return collections from methods instead of using a prebuilt collection class (your C# bodies will never know what hit them):

static IEnumerable<int> GetPrimes(int first, int last) {

   for(int n = first; n <= last; n++) {

      int limit = (int)Math.Sqrt(n);

      bool isprime = true;

      for(int i = 2; i <= limit; i++)

         if(n % i == 0) {

            isprime = false;

            break;

         }

      if(isprime)

         yield return n;

   }

}

8. Override Object.GetHashCode for your own types, even if you don’t plan to use them as keys in a dictionary (don’t forget to override Object.Equals in this case, and if someone asks, explain why this is soooooo cool).

9. Create generic types whenever possible, and throw in a good constraint or two to baffle your fellow programmers.

10. Use Nullable<T> in its C# form (T?) and watch the question mark on your peers’ faces:

DateTime? dt = DateTime.Now.Second % 2 == 0 ? DateTime.Now : (DateTime?)null;

Console.WriteLine(dt);      // what's gonna show up?

 

This is my list… what’s yours?