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.
- Part 1 : Extension methods and Linq
- Part 2 : Try Catch and reusability
- Part 3 : C# 3 shortcuts
- Part 4 : Chainable methods
- Part 5 : Parsing and conversion
- Part 6 : Contructor with initializer and event setters
- Part 7 : Post compilation
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; }
}