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 strongly 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. }
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Technorati
  • TwitThis

Write a comment