Concise C# Part 3 : C# 3 shortcuts

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

//Verbose and Ugly
Post value = new Post();
value.Title = "New Version For C#";
value.CreatedOn = DateTime.Now;
CreatePost(value);

//Concise and Sweet
CreatePost(new Post
{
    Title = "NewVersion For C#",
    CreatedOn = DateTime.Now
});

Collection initializers

//Verbose and Ugly
var names = new List();
names.Add("manitra");
names.Add("yeah");
SaveNames(names);

//Concise and Sweet
SaveNames(new List { "manitra", "yeah" });

Var keyword

//Verbose and Ugly
Dictionary> result = new Dictionary>();

//Concise and Sweet (But still strongly typed)
var result = new Dictionary>();

Automatic properties

//Verbose and Ugly
public class Post
{
    private string title;
    private string description;
    private DateTime createdOn;

    public string Title
    {
        get
        {
            return this.title;
        }
        set
        {
            this.title = value;
        }
    }

    public string Description
    {
        get
        {
            return this.description;
        }
        set
        {
            this.description = value;
        }
    }

    public System.DateTime CreatedOn
    {
        get
        {
            return this.createdOn;
        }
        set
        {
            this.createdOn = value;
        }
    }
}

//Concise and Sweet
public class Post
{
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime CreatedOn { get; set; }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.