Skip to content

Instantly share code, notes, and snippets.

@jand187
Last active November 3, 2021 18:14
Show Gist options
  • Save jand187/cabd16971097b5beb4c3 to your computer and use it in GitHub Desktop.
Save jand187/cabd16971097b5beb4c3 to your computer and use it in GitHub Desktop.
Generic builder with extensions
public class GenericBuilder<TEntity> where TEntity : new()
{
private readonly List<Func<TEntity, object>> setters;
public GenericBuilder()
{
setters = new List<Func<TEntity, object>>();
}
public GenericBuilder<TEntity> With(params Func<TEntity, object>[] props)
{
setters.AddRange(props);
return this;
}
public TEntity Build()
{
var model = new TEntity();
setters.ForEach(s => s.Invoke(model));
return model;
}
}
public class Person
{
public string Name { get; set; }
public Gender Gender { get; set; }
public int Age { get; set; }
}
public enum Gender
{
Undefined,
Male,
Female
}
public class Employee : Person
{
public Company Employer { get; set; }
public decimal MonthlySalary { get; set; }
public Company SetEmployer(Company employer)
{
Employer = employer;
if (!employer.Employees.Contains(this))
employer.Employees.Add(this);
return employer;
}
}
public class Company
{
public Company()
{
Employees = new List<Employee>();
}
public string Name { get; set; }
public Ownership Ownership { get; set; }
public List<Employee> Employees { get; set; }
public Employee AddEmployee(Employee employee)
{
Employees.Add(employee);
return employee;
}
}
public enum Ownership
{
Undefined,
Private,
Public
}
public static class EmployeeBuilderExtesions
{
public static GenericBuilder<Person> Man(this GenericBuilder<Person> @this)
{
@this.With(person => person.Gender = Gender.Male);
@this.With(person => person.Age = 18);
return @this;
}
}
public static class CompanyBuilderExtesions
{
public static GenericBuilder<Company> FordMotor(this GenericBuilder<Company> @this)
{
@this.With(company => company.Name = "Ford Motor Company");
@this.With(company => company.Ownership = Ownership.Private);
return @this;
}
}
public class EntryPoint
{
[Test]
public void SomeTest()
{
var model = new GenericBuilder<Employee>()
.With(
e => e.Name = "Hansemand",
e => e.Age = 80,
e => e.SetEmployer(new GenericBuilder<Company>()
.FordMotor()
.Build())
)
.Build();
var sss = "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment