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");
a9c10815-4932-49f9-8d57-2f1ccff0acf2|0|.0