Wednesday, September 24, 2008

Prevent indentation by combining using-statements

C# code tends to be heavily indented:

  • All code is indented at least three levels deep (namespace, class, method).
  • The usage of constructs such as using and try-finally adds further indentation.

Especially in GDI+ drawing code, the usage of using-statements can make the code much more difficult to read:

   1: protected override void OnPaint(PaintEventArgs e)
   2: {
   3:     base.OnPaint(e);
   4:  
   5:     using (Pen thickBlack = new Pen(Color.Black, 5f))
   6:     {
   7:         using (Pen thickRed = new Pen(Color.Red, 5f))
   8:         {
   9:             using (LinearGradientBrush backGround = new LinearGradientBrush(...)
  10:             {
  11:                 // start painting here...
  12:             }
  13:         }
  14:     }
  15: }

This can be simplified by combining the using-statements like this:

   1: protected override void OnPaint(PaintEventArgs e)
   2: {
   3:     base.OnPaint(e);
   4:  
   5:     using (Pen thickBlack = new Pen(Color.Black, 5f))
   6:     using (Pen thickRed = new Pen(Color.Red, 5f))
   7:     using (LinearGradientBrush backGround = new LinearGradientBrush(...)
   8:     {
   9:         // start painting here...
  10:     }
  11: }

As you can see this reduces indentation, making the code easier to read and understand.

6 comments:

Anonymous said...

Hello,

Congratulation for your blog; you have written some very interesting posts.

I really love the way C# source code is displayed on your blog. Can you tell me what you are using for syntax highlighting ?

Regards.

Kristof said...

@anonymous: Thanks, I'm glad you like my blog!
I use Windows Live Writer to write my posts, and I am generally happy with it.

The source code is formatted using the 'code snippet plugin' which can be found here:
http://lvildosola.blogspot.com/2007/02/code-snippet-plugin-for-windows-live.html.

Luke Puplett said...

I recently came across your blog (google search on something) and have learnt a few things from just your most recent entries, so I second the above comment in congratulating you.

I particularly appreciate that you don't feel anything is too mundane to post, believing that there are learners out there at all levels, and that experienced programmers often do miss a trick or three.

Loved the 'stacked' using statements!! Its the sort of thing you see in someone else's source and quietly think "Woah. I didn't know you could do that!"

ch1c0 s4b10 said...

Good simple tips, very useful.

Dan said...

Thank you! I was looking for a way to make my code a bit more maintainable.

Anonymous said...

//how about that?
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Pen thickBlack = new Pen(Color.Black, 5f),Pen thickRed = new Pen(Color.Red, 5f),LinearGradientBrush backGround = new LinearGradientBrush(...))
{
// start painting here...
}
}