Concise C# Part 3 : C# 3 shortcuts

Posted on : 07-09-2009 | By : manitra | In : C#

0

The version 3 of C# brings us a lot of syntactic sugar to reduce the length of our code. Here are some of them.

This post is part of a serie about making C# code shorter.

Constructors with Property initializers

  1. //Verbose and Ugly
  2. Post value = new Post();
  3. value.Title = "New Version For C#";
  4. value.CreatedOn = DateTime.Now;
  5. CreatePost(value);
  6.  
  7. //Concise and Sweet
  8. CreatePost(new Post
  9. {
  10.     Title = "NewVersion For C#",
  11.     CreatedOn = DateTime.Now
  12. });

Collection initializers

  1. //Verbose and Ugly
  2. var names = new List<string>();
  3. names.Add("manitra");
  4. names.Add("yeah");
  5. SaveNames(names);
  6.  
  7. //Concise and Sweet
  8. SaveNames(new List<string> { "manitra", "yeah" });

Var keyword

  1. //Verbose and Ugly
  2. Dictionary<string, List<Post>> result = new Dictionary<string, List<Post>>();
  3.  
  4. //Concise and Sweet (But still trongly typed)
  5. var result = new Dictionary<string, List<Post>>();

Automatic properties

  1. //Verbose and Ugly
  2. public class Post
  3. {
  4.     private string title;
  5.     private string description;
  6.     private DateTime createdOn;
  7.  
  8.     public string Title
  9.     {
  10.         get
  11.         {
  12.             return this.title;
  13.         }
  14.         set
  15.         {
  16.             this.title = value;
  17.         }
  18.     }
  19.  
  20.     public string Description
  21.     {
  22.         get
  23.         {
  24.             return this.description;
  25.         }
  26.         set
  27.         {
  28.             this.description = value;
  29.         }
  30.     }
  31.  
  32.     public System.DateTime CreatedOn
  33.     {
  34.         get
  35.         {
  36.             return this.createdOn;
  37.         }
  38.         set
  39.         {
  40.             this.createdOn = value;
  41.         }
  42.     }
  43. }
  44.  
  45. //Concise and Sweet
  46. public class Post
  47. {
  48.     public string Title { get; set; }
  49.     public string Description { get; set; }
  50.     public DateTime CreatedOn { get; set; }
  51. }

Concise C# Part 2 : Try Catch and reusability

Posted on : 03-09-2009 | By : manitra | In : C#

0

Exception handling is an important part of any software. In this post, I will talk about a trick to make but some kind of reusability on exception handling.

This post is part of a serie about making C# code shorter

When you write code, you usually try to reuse your code by creating methods and calling those methods each time you the need their functionality. When working with exceptions, it’s a bit tricky because, they don’t follow the normal code flow, they jump out of your method … unless you catch them. The consequence is that you usually have multiple similar try {} catch {} blocks that are often copied and pasted.

This is what usually happens

  1. public void Method1()
  2. {
  3.     try
  4.     {
  5.         //method 1 content
  6.     }
  7.     catch (ThreadAbortException)
  8.     {
  9.     }
  10.     catch (IOException ex)
  11.     {
  12.         //IO exception handling
  13.     }
  14.     finally
  15.     {
  16.         //add any code for releasing ressource
  17.     }
  18. }
  19.  
  20. public void Method2()
  21. {
  22.     try
  23.     {
  24.         //method 2 content
  25.     }
  26.     catch (ThreadAbortException)
  27.     {
  28.     }
  29.     catch (IOException ex)
  30.     {
  31.         //IO exception handling
  32.     }
  33.     finally
  34.     {
  35.         //add any code for releasing ressource
  36.     }
  37. }

The solution to reuse the exception block

This is what you could do to reuse the same error handling code block in c# :

  1. public void Method1()
  2. {
  3.     Do(() =>
  4.     {
  5.         //method 1 content
  6.     });
  7. }
  8.  
  9. public void Method2()
  10. {
  11.     Do(() =>
  12.     {
  13.         //method 2 content
  14.     });
  15. }
  16.  
  17. protected void Do(Action method)
  18. {
  19.     try
  20.     {
  21.         //code to call before each methods
  22.         method();
  23.         //code to call after each methods success
  24.     }
  25.     catch (ThreadAbortException)
  26.     {
  27.     }
  28.     catch (IOException ex)
  29.     {
  30.         //IO exception handling
  31.     }
  32.     finally
  33.     {
  34.         //add any code for releasing ressource
  35.     }
  36. }

Concise C# Part 1 : Extension methods and Linq

Posted on : 27-08-2009 | By : manitra | In : C#

0

Because, short code is easier to understand, I decided to publish some posts about making C# code shorter. I’ll talk about small tricks I use to significantly reduce the amount of code I write to achieve my goals. Some people don’t agree with that idea because there has been abuses done by perl and c programmer in the past. I think that, if you use correct names for methods, variable and types, the shortest code will still be easy to understand.

This post is part of a serie about making C# code shorter

In this post, I’ll use the following class for my examples :

  1. public class Post
  2. {
  3.     public int Id { get; set; }
  4.     public string Author { get; set; }
  5.     public string Title { get; set; }
  6.     public string Content { get; set; }
  7. }

Linq extension methods

Linq is a set of contracts (interfaces) wich allow the developper to request objects from a data store. What make it unique is that :
- the query language is strongly typed (at compile time you are sure that all column names et types are corrects and that there are no missin semi-colon
- it supports unlimited data store type (including all database systems, xml files, google data, twitter posts, in memory objects …)

I’ll focus primarily on Linq to Objects (in memory object) because we’re talking about making code concise. So here are the shortcuts !

Searching an unique element in a collection

  1. //Concise and Sweet
  2. public Post GetById(int id, IList<Post> posts)
  3. {
  4.     return posts.FirstOrDefault(p => p.Id == id);
  5. }
  6.  
  7. //Verbose and Ugly
  8. public Post GetById(int id, IList<Post> posts)
  9. {
  10.     foreach (Post current in posts)
  11.     {
  12.         if (current.Id == id)
  13.         {
  14.             return current;
  15.         }
  16.     }
  17. }

Filtering a collection

  1. //Concise and Sweet
  2. public IList<Post> FindByAuthor(string author, IList<Post> posts)
  3. {
  4.     return posts.Where(p => p.Author == author).ToList();
  5. }
  6.  
  7. //Verbose and Ugly
  8. public IList<Post> FindByAuthor(string author, IList<Post> posts)
  9. {
  10.     List<Post> result = new List<Post>();
  11.     foreach (Post current in posts)
  12.     {
  13.         if (current.Author == author)
  14.         {
  15.             result.Add(current);
  16.         }
  17.     }
  18.     return result;
  19. }

Selecting a column (one property of an object collection)

  1. //Concise and Sweet
  2. public IList<string> ExtractTitles(IList<Post> posts)
  3. {
  4.     return posts.Select(p => p.Title).ToList();
  5. }
  6.  
  7. //Verbose and Ugly
  8. public IList<string> ExtractTitles(IList<Post> posts)
  9. {
  10.     List<string> result = new List<string>();
  11.     foreach (Post current in posts)
  12.     {
  13.         result.Add(current.Title);
  14.     }
  15.     return result;
  16. }

Apply changes to a collection

  1. //Concise and Sweet
  2. public IList<Post> Anonymize(IList<Post> posts)
  3. {
  4.     return posts.Select(p => new Post
  5.     {
  6.         Id = p.Id,
  7.         Title = p.Title,
  8.         Author = "***",
  9.         Content = p.Content
  10.     }).ToList();
  11. }
  12.  
  13. //Verbose and Ugly
  14. public IList<Post> Anonymize(IList<Post> posts)
  15. {
  16.     List<Post> result = new List<Post>();
  17.     foreach (Post current in posts)
  18.     {
  19.         Post anonymousPost = new Post();
  20.         anonymousPost.Id = current.Id;
  21.         anonymousPost.Title = current.Title;
  22.         anonymousPost.Author = "***";
  23.         anonymousPost.Content = current.Content;
  24.         result.Add(anonymousPost);
  25.     }
  26.     return result;
  27. }

Creating your own extension methods

Extension methods are the best candidates when you plan to build your very own low level toolset. Here are some examples to give you an idea.

  1. public static class MyExtensions
  2. {
  3.     //Index a collection by its key
  4.     public static IDictionary<TKey, TObject> IndexBy<TObject, TKey>(this IEnumerable<TObject> target, Func<TObject, TKey> keyExtractor)
  5.     {
  6.  
  7.         var result = new Dictionary<TKey, TObject>();
  8.         foreach (var current in target)
  9.             result[keyExtractor(current)] = current;
  10.         return result;
  11.     }
  12.  
  13.     //Joining any collection of string (array, list, enumerable …)
  14.     public static string Join(this IEnumerable<string> elements, string separator)
  15.     {
  16.         return string.Join(separator, elements.ToArray());
  17.     }
  18. }

Asynchronous tasks on Winform

Posted on : 11-05-2009 | By : manitra | In : C#, Developpement, WinForm

2

The problem

When you create winform applications, doing tasks in the background is essential to avoid user frustation. Unfortunatly, it could make you write a lot more code. Here are some utility methods that reduce the complexity of asynchronous calls within windows forms.

Within you base class

You probably have a common base class for all your UI components. Add these methods :

  1. namespace TestWinForm
  2. {
  3.     public class BaseForm : Form
  4.     {
  5.         // Execute some code in async mode.
  6.         // When it's done, it calls the nextStep delegate, eventually with
  7.         // an exception catched during the main action.
  8.         protected virtual void Async(Action action, Action nextStep)
  9.         {
  10.             new Thread(delegate()
  11.             {
  12.                 Exception exception = null;
  13.                 try
  14.                 {
  15.                     action();
  16.                 }
  17.                 catch (Exception ex)
  18.                 {
  19.                     exception = ex;
  20.                 }
  21.                 ThreadSafe(() =&gt; { nextStep(exception ); });
  22.             }).Start();
  23.         }
  24.  
  25.         // This allows a sub class to easily run a method within
  26.         // an UI thread without the need of creating multiple
  27.         // delegate signatures for each method signatures
  28.         protected virtual void ThreadSafe(MethodInvoker method)
  29.         {
  30.             if (InvokeRequired)
  31.                 Invoke(method);
  32.             else
  33.                 method();
  34.         }
  35.     }
  36. }

Within your UI classes

Now the only thing you need to do is to encapsulate the methode content with the Async() method :

namespace TestWinForm
  1. {
  2.     public partial class MainForm : BaseForm
  3.     {
  4.         public MainForm()
  5.         {
  6.             InitializeComponent();
  7.         }
  8.  
  9.         // Here is the async trick :
  10.         // – UI will NOT freeze,
  11.         // – you can add beautifull animated gifs
  12.         private void button1_Click(object sender, EventArgs e)
  13.         {
  14.             DateTime? result = null;
  15.             Async(
  16.                 () =&gt;
  17.                 {
  18.                     result = GetComplexDate();
  19.                 },
  20.                 (ex) =&gt;
  21.                 {
  22.                     if (ex == null)
  23.                         textBox1.Text = result.Value.ToShortDateString();
  24.                     else
  25.                         textBox1.Text = ex.Message;
  26.                 }
  27.             );
  28.         }
  29.  
  30.         // This is the slow, data-intensive task :p
  31.         private DateTime? GetComplexDate()
  32.         {
  33.             Thread.Sleep(3000);
  34.             return DateTime.Now;
  35.         }
  36.     }
  37. }

The traditional way

Just in case you didn’t get it. This is what you should NOT DO:

// This was traditional way :
  1.         // – UI will freeze until during 3 second …
  2.         // – you users will complain
  3.         // avoid this !
  4.         private void button1_Click2(object sender, EventArgs e)
  5.         {
  6.             try
  7.             {
  8.                 textBox1.Text = GetComplexDate().ToShortDateString();
  9.             }
  10.             catch (Exception ex)
  11.             {
  12.                 textBox1.Text = ex.Message;
  13.             }
  14.         }

Happy coding !

Make InvokeRequired/Invoke easy

Posted on : 23-01-2009 | By : manitra | In : C#, Developpement, WinForm

5

The problem

If you’re working on WinForms, you must know that you cannot call controls methods within a thread that is not the one that created those controls. To solve this problem, Microsoft recommend us to use the following code :

  1. namespace TestWinForm
  2. {
  3.     public partial class MainForm : BaseForm
  4.     {
  5.         public MainForm()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.         // a delegate that has been created specially for this method
  10.         private delegate void DisplayDelegate(string text);
  11.  
  12.         // a method that may be called from a worker thread
  13.         public virtual void Display(string text)
  14.         {
  15.             if (InvokeRequired)
  16.             {
  17.                 Invoke(new DisplayDelegate(Display));
  18.             }
  19.             else
  20.             {
  21.                 //the actual job is here
  22.                 textBox1.AppendText(text);
  23.             }
  24.         }
  25.     }
  26. }

This code is ugly because :

  • you need to create a delegate for each single public method you can call from outside
  • you need to put an “if/else” block in each method wich increase the complexity of your code

The trick

Here is a trick that could significantly reduce the amount of code needed to do the same job within a large project.

Within you base class

You probably have a common base class for all your UI components. Add this method :

  1. namespace TestWinForm
  2. {
  3.     public class BaseForm : Form
  4.     {
  5.         // This allows a sub class to easily run a method within
  6.         // an UI thread without the need of creating multiple
  7.         // delegate signatures for each method signatures
  8.         protected virtual void ThreadSafe(MethodInvoker method)
  9.         {
  10.             if (InvokeRequired)
  11.                 Invoke(method);
  12.             else
  13.                 method();
  14.         }
  15.     }
  16. }

Within your UI classes

Now the only thing you need to do is to encapsulate the methode content with the ThreadSafe() method :

  1. namespace TestWinForm
  2. {
  3.     public partial class MainForm : BaseForm
  4.     {
  5.         public MainForm()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         // public method that may be called from outside and within any
  11.         // worker thread …
  12.         public virtual void Display(string text)
  13.         {
  14.             ThreadSafe(delegate
  15.             {
  16.                 //do any UI related code here
  17.                 //note that because this is an anonym method,
  18.                 //you can use the local parameter
  19.                 textBox1.AppendText(text);
  20.             });
  21.         }

Happy coding !