Fun With Extension Method and Fluent Interface

Since C# 3.0, object initializer has been my favourite.
Given the following class:

public class Book
{
    public string Isbn {get;set;}
    public string Title {get; set;}
    public string Author {get; set;}
    public int TotalPages {get;set;}
    public void Save()
    {
	//some persistent logic
    }
}

Prior to C# 3.0 you’ll normally use the following codes:

Book book=new Book();
book.Isbn="1284848395";
book.Title="What the hell?";
book.Author="Unknown";
book.TotalPages=40;
book.Save();

Tiresome, right? Consider the following statement:

new Book{
    Isbn="1284848395", Title="What the hell?",
    Author="Unknown",TotalPages=40
}.Save();

We get the same result with only 1 statement. Now what happened if your variable is not initialized directly, but taken from other method, let’s say getter or perhaps factory method. You’ll still need to code with old style. What if you are a fluent interface lover so you want 1 statement only.

We can use this.

public static T Do<T>(this T o,Action<T> action)
{
    action(o);
    return o;
}

Notice how we call it:

GetBook().Do<Book>(b=>{
   b.Isbn="1284848395"; b.Title="What the hell?"; 
   b.Author="Unknown";b.TotalPages=40;        
}).Save();

It is certainly more verbose, but if 1 statement is what you’re after then it works.
You can also refactor anonymous method into a concrete method since it will make code cleaner.