Reputation: 3506
So if you take a look at any of the Append methods of a 'StringBuilder', the return type is StringBuilder
. Not a string or a count of lines or anything you might think could be even intuitively useful. Ostensibly (I haven't checked this yet), it's the same StringBuilder
object that you just called the method on.
I can't really see a reason for that. Is there one?
Upvotes: 2
Views: 468
Reputation: 17185
This is a simple form of what is called a "fluent interface" or "fluent API". (see This wikipedia article) APIs following that pattern allow chaining of methods, which may look weird in the beginning, but may make the code natural to read. Another well-known API implementing this is linq
, where you can write things like
myList.Where(x => x.Element1 > 1).OrderBy(x => x.Element2).Select(x => x.Element3);
Or, as a really sophisticated sample of a fluent API, a task description from Nuke build:
Target CompileForMatlab => _ => _
.Executes(() =>
{
MSBuild(s => s
.SetSolutionFile(Solution)
.SetConfiguration(Configuration)
.AddTargets("Restore,Build,Publish")
.SetProjectFile(Solution.GetProject("ExtendedLogParser"))
.SetOutDir(ArtifactsDirectory / "ExtendedLogParser")
.SetProperty("Platform", Platform)
.AddProperty("SelfContained", true)
.AddProperty("RuntimeIdentifier", "win10-x64")
.AddProperty("PublishDir", "../ExtendedLogParser")
.DisableNodeReuse());
});
Upvotes: 4