DCSIMG
How to be a Cool C# Programmer - 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

How to be a Cool C# Programmer

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?

Comments List

# re: How to be a Cool C# Programmer

Published at Wednesday, July 21, 2010 9:54 AM by aviade  

Great post, Thanks!

Keep it up!

# re: How to be a Cool C# Programmer

Published at Wednesday, July 21, 2010 12:45 PM by kick(_o_)  

liked the underscore thingy

thanks

# re: How to be a Cool C# Programmer

Published at Wednesday, July 21, 2010 3:06 PM by Yoramo  

I prefer KISS (Keep It Simple Stupid) on cool.

# re: How to be a Cool C# Programmer

Published at Thursday, July 22, 2010 7:44 AM by Shachar Bar  

Great stuff :)

# re: How to be a Cool C# Programmer

Published at Saturday, August 07, 2010 7:57 PM by Nach  

Didn't help with the chicks

# re: How to be a Cool C# Programmer

Published at Wednesday, August 11, 2010 5:29 PM by Henry Aloni  

I must say:

After following your tips for 8 hours I got a bunch of completely unreadable and therefore unmaintainable code.

# re: How to be a Cool C# Programmer

Published at Wednesday, August 11, 2010 6:24 PM by Pavel  

Henry,

I guess you won't be that cool... :)

But, seriously, if you understand, say, LINQ, then using LINQ is very clear and maintainable.

Try the grouping example in plain C# and see for yourself.

# re: How to be a Cool C# Programmer

Published at Sunday, October 03, 2010 2:03 PM by Omer Agmon  

My list:

1. Use rare keywords as much as you can. Try to combine it with unreadable code. For example:

var c = a ?? b ?? (object)1 ?? (object)2;

or

using MyType = System.Windows.Forms.DataFormats; // outside class declaration

or

public volatile int i;

2. Create variables with the same name as keywords ;)

string @string = "Hi";

3. Always use global::

var a = global::System.String.Empty;

4. use __arglist instead of specifying typed parameters! it's cool!

public void test(__arglist)

       {

           ArgIterator iterator = new ArgIterator(__arglist);

           TypedReference tf = iterator.GetNextArg();

           var firstArgument = TypedReference.ToObject(tf);

       }

and then:

test(__arglist(5, 5.5, "Hello", new Dictionary<int, float>()));

5. Last but not least, always check your arithmetic calculations...

int i = checked(Int32.MaxValue + 1);

That's it for today :)

# re: How to be a Cool C# Programmer

Published at Tuesday, November 29, 2011 11:59 AM by Eric Stephen  

Thanks for your information, i really appreciate it..

Leave a Comment

(required) 
(
required
)
 
(optional)
(required) 

Enter the numbers above: