Skip to content

Instantly share code, notes, and snippets.

@thinkingserious
Last active May 10, 2016 16:26
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 thinkingserious/237e370ee747f5b8403650f0c794617e to your computer and use it in GitHub Desktop.
Save thinkingserious/237e370ee747f5b8403650f0c794617e to your computer and use it in GitHub Desktop.
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