This is a mirror of official site: http://jasper-net.blogspot.com/

How to be a Cool C# Programmer

| Wednesday, July 21, 2010
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);
}

Read more: Pavel's Blog

Posted via email from .NET Info

0 comments: