Created
December 9, 2021 09:50
-
-
Save alex-oswald/9679390662b1c085f7cfd9698b27d549 to your computer and use it in GitHub Desktop.
Fluent builder example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var person = PersonBuilder.Create() | |
.Age(30) | |
.FirstName("First") | |
.LastName("Last") | |
.Build(); | |
Console.WriteLine(person); | |
public interface IPersonBuilder | |
{ | |
Person Build(); | |
IPersonBuilder FirstName(string value); | |
IPersonBuilder LastName(string value); | |
IPersonBuilder Age(int age); | |
} | |
public sealed class PersonBuilder : IPersonBuilder | |
{ | |
private Person _person; | |
public PersonBuilder() | |
{ | |
_person = new Person(); | |
} | |
public static IPersonBuilder Create() => new PersonBuilder(); | |
public Person Build() => _person; | |
public IPersonBuilder FirstName(string value) | |
{ | |
_person.FirstName = value; | |
return this; | |
} | |
public IPersonBuilder LastName(string value) | |
{ | |
_person.LastName = value; | |
return this; | |
} | |
public IPersonBuilder Age(int age) | |
{ | |
_person.Age = age; | |
return this; | |
} | |
} | |
public record Person | |
{ | |
public string FirstName { get; set; } = ""; | |
public string LastName { get; set; } = ""; | |
public int? Age { get; set; } | |
public override string ToString() | |
{ | |
return $"{LastName}, {FirstName} {Age}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment