Skip to content

Instantly share code, notes, and snippets.

@thinkingserious thinkingserious/Fluent.cs
Last active May 10, 2016

Embed
What would you like to do?
Fluent Interface in C# Using Method Chaining and Reflection
using System;
using System.Dynamic;
namespace Fluent
{
class Client : DynamicObject
{
public string UrlPath;
public Client(string urlPath = null)
{
UrlPath = (urlPath != null) ? urlPath : null;
}
private Client BuildClient(string name = null)
{
string endpoint;
if (name != null)
{
endpoint = UrlPath + "/" + name;
}
else
{
endpoint = UrlPath;
}
UrlPath = null; // Reset the current object's state before we return a new one
return new Client(endpoint);
}
public Client _(string name)
{
return BuildClient(name);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = BuildClient(binder.Name);
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = UrlPath;
return true;
}
}
class Program
{
static void Main(string[] args)
{
dynamic client = new Client();
dynamic chain = client.hello.world;
Console.WriteLine(chain.UrlPath);
Console.ReadLine();
dynamic new_chain = chain.thanks._("for").all.the.fish;
Console.WriteLine(new_chain.method());
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.