If you are building domain entities, or other important classes, having a custom builder class with intention-revealing method (e.g. WithFirstName) provides terseness (avoiding lambda expressions) and allows the builder class to start forming documentation about the usage of that object.
Sometimes though, you just want to build a class without that ceremony. Typically, we find that this applies for view models and DTOs.
In that instance you can use the generic
Builder implementation as shown below:
StudentViewModel vm = Builder<StudentViewModel>.CreateNew() .Set(x => x.FirstName, "Pi") .Set(x => x.LastName, "Lanningham") .Set(x => x.EnrollmentDate, new DateTime(2000, 1, 1)); var studentViewModels = Builder<StudentViewModel>.CreateListOfSize(5) .TheFirst(1).Set(x => x.FirstName, "First") .TheNext(1).Set(x => x.LastName, "Next Last") .TheLast(1).Set(x => x.LastName, "Last Last") .ThePrevious(2).With(b => b.Set(x => x.LastName, "last" + (++i).ToString())) .All().Set(x => x.EnrollmentDate, _enrollmentDate) .BuildList();
The syntax is modelled closely against what NBuilder provides and the behaviour of the class should be very similar.
Note, that in the first example above, it was not necessary to call the
Build method at the end of the method chain. This is because the
vm variable has been defined as
StudentViewModel and the C# compiler is able to infer the type and the object is set implicitly.
In the second example, the
var keyword is used to define
studentViewModels, and so it is necessary to explicitly call
BuildList to set the variable.
By default, the longest constructor of the class you specify will be called and then all properties (with public and private setters) will be set with values you specified (or anonymous values if none were specified).
Sometimes you might not want this behaviour, in which case you can specify a custom construction factory (see Build objects without calling constructor section for explanation of factories) as shown below:
var dto = Builder<MixedAccessibilityDto> .CreateNew(new CallConstructorFactory()) .Build(); var dtos = MixedAccessibilityDto dto = Builder<MixedAccessibilityDto> .CreateListOfSize(5, new CallConstructorFactory()) .BuildList();
See the documentation about the SetUsingBuilder method.
Updated less than a minute ago