Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Last active October 29, 2020 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MelbourneDeveloper/0d7e39e5005b706b0dbf57696ec7aee5 to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/0d7e39e5005b706b0dbf57696ec7aee5 to your computer and use it in GitHub Desktop.
Fluent API design with immutable type. From https://dotnettutorials.net/lesson/fluent-interface-design-pattern/
using System;
namespace FluentInterfaceDesignPattern
{
class Program
{
static void Main(string[] args)
{
var obj = EmployeeExtensions.CreateEmployee(default, default, default, default);
obj = obj.NameOfTheEmployee("Anurag Mohanty")
.Born("10/10/1992")
.WorkingOn("IT")
.StaysAt("Mumbai-India");
Console.WriteLine($"Name: {obj.FullName} DOB: {obj.DateOfBirth} Department: {obj.Department} Address: {obj.Address}");
Console.Read();
}
}
public interface IEmployee
{
string FullName { get; }
DateTime DateOfBirth { get; }
string Department { get; }
string Address { get; }
}
internal class EmployeeRecord : IEmployee
{
public string FullName { get; }
public DateTime DateOfBirth { get; }
public string Department { get; }
public string Address { get; }
public EmployeeRecord(
string fullName,
DateTime dateOfBirth,
string department,
string address
)
{
FullName = fullName;
DateOfBirth = dateOfBirth;
Department = department;
Address = address;
}
}
public static class EmployeeExtensions
{
public static IEmployee CreateEmployee(string fullName,
DateTime dateOfBirth,
string department,
string address) => new EmployeeRecord(fullName, dateOfBirth, department, address);
public static IEmployee NameOfTheEmployee(this IEmployee employee, string fullName) => CreateEmployee(fullName, employee.DateOfBirth, employee.Department, employee.Address);
public static IEmployee Born(this IEmployee employee, string dateOfBirth) => CreateEmployee(employee.FullName, Convert.ToDateTime(dateOfBirth), employee.Department, employee.Address);
public static IEmployee WorkingOn(this IEmployee employee, string department) => CreateEmployee(employee.FullName, employee.DateOfBirth, department, employee.Address);
public static IEmployee StaysAt(this IEmployee employee, string address) => CreateEmployee(employee.FullName, employee.DateOfBirth, employee.Department, address);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment