https://github.com/jukkahyv/sample-nested-builder-csharp
Sample for nested builder pattern in C#
https://github.com/jukkahyv/sample-nested-builder-csharp
builder-pattern csharp
Last synced: 2 months ago
JSON representation
Sample for nested builder pattern in C#
- Host: GitHub
- URL: https://github.com/jukkahyv/sample-nested-builder-csharp
- Owner: jukkahyv
- License: mit
- Created: 2019-12-21T14:08:31.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2020-01-03T14:39:45.000Z (almost 6 years ago)
- Last Synced: 2025-02-13T12:42:27.635Z (11 months ago)
- Topics: builder-pattern, csharp
- Language: C#
- Size: 8.79 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Sample for nested builder pattern in C#
Making use of Action callbacks and "out" parameters, with optional discards.
```csharp
var docTree = new DocumentTreeBuilder()
.AddFolder("My files", folder => folder
.SetIcon("myicon.png")
.AddDocument(Model.DocumentType.Text)
.AddDocument(Model.DocumentType.Text)
.AddDocument(Model.DocumentType.Text, out var textDocument)
.AddSubFolder("Images", imgFolder => imgFolder
.AddDocument(Model.DocumentType.Image, doc => doc.AddLink(textDocument))
)
, out var myFiles)
.AddFolder("Shared files")
.Build();
Console.WriteLine($"MyFiles ID: {myFiles.Id}");
```
## Some explanation
One of the rules I follow is that the builder methods (such as ```AddDocument```) should always return the builder itself, and
the child builder, if necessary, should be accessed in a callback. This makes it clear when we are configuring a child object, and when parent object, and avoids the need to use special GetParent or Build calls.
The children can be chained easily.
Additionally, all created objects can be exported as "out" parameters, if they need to be accessed later.