Tags: , | Categories: C#, Fluent Posted by Admin on 9/21/2011 8:17 AM | Comments (0)

A while ago we wrote about fluent apis using interfaces, this is probably the 'text book' approach but since we're about real web development lets have a real world approach.

public class Country
{
    // backing field for the name property.
    private string name = string.Empty;

    // backing field for the code property;
    private string code = string.Empty;

    // accessor to the name backing field. The setter is private.
    public string Name
    {
        get { return this.name; }
        private set { this.name = value; }
    }

    // accessor to the code backing field. The setter is private.
    public string Code
    {
        get { return this.code; }
        private set { this.code = value; }
    }

    // chainable (fluent) method to set the name. Note this returns to instance of the entity whose property is being set.
    public Country WithName(string name)
    {
        this.Name = name;
        return this;
    }

    // chainable (fluent) method to set the code. Note this returns to instance of the entity whose property is being set.
    public Country WithCode(string code)
    {
        this.Code = code;
        return this;
    }
}

So if we were to use this class within an application we can now write code like

Country unitedKingdom = new Country().WithName("United Kingdom").WithCode("UK");

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading