0

Referring to the example below, what is going on when the new logger is created? Several lines start with a ".". I'm guessing this is object initialization, but it doesn't seem like normal constructor arguments.

What is this syntax doing?

enter image description here

Izzo
  • 4,461
  • 13
  • 45
  • 82
  • 1
    If you delete the whitespace (which is largely ignored by the compiler), do you understand the line then? – Hans Kesting Jan 09 '20 at 15:52
  • Given the fact that the `;` terminates your line, and the fact that you already have `.MinimumLevel.Verbose()` as an example it should be relatively apparent to you. No? It is just one long line of code split on several lines. – Andrew Truckle Jan 09 '20 at 15:54
  • @HansKesting I understand that whitespace is ignored, but it seems like an odd way to create an object. Why not just have input arguments for each setting? – Izzo Jan 09 '20 at 15:58
  • 1
    See also: https://softwareengineering.stackexchange.com/questions/69519/when-to-go-fluent-in-c, https://stackoverflow.com/questions/2084503/whats-a-fluent-interface, https://stackoverflow.com/questions/17937755/what-is-the-difference-between-a-fluent-interface-and-the-builder-pattern/17937946 – canton7 Jan 09 '20 at 16:00

2 Answers2

8

This is just a chain of methods and properties. You can take:

something.A.B().C.D().E.F();

And add newlines to write it as:

something
    .A.B()
    .C.D()
    .E.F();

More generally, this style of method chaining to configure an object is called a Fluent Interface.

canton7
  • 37,633
  • 3
  • 64
  • 77
  • You learnt me how it was called. Thank you ! Just adding [this post](https://assist-software.net/blog/design-and-implement-fluent-interface-pattern-c) in my comment as it illustrates with an example – WilliamW Jan 09 '20 at 15:59
  • Why is it necessary to create an object this way though? Why not just input arguments for each setting? – Izzo Jan 09 '20 at 15:59
  • @Izzo The designer of that interface decided that it was a nicer (i.e. cleaner, easier to read and write) way of configuring the builder than calling individual methods or having lots of input arguments. I've added some links to a comment on your OP. – canton7 Jan 09 '20 at 16:01
2

The object is created here:

new LoggerConfiguration()

The next part is accessing a property on the new object:

.MinimumLevel

Followed by a method call on the object referenced by that property:

.Verbose()

And so on.

The entire statement represents a single expression, the result of which is assigned to the variable logger.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35