Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active November 7, 2019 14:17
Show Gist options
  • Save gsscoder/4626716 to your computer and use it in GitHub Desktop.
Save gsscoder/4626716 to your computer and use it in GitHub Desktop.
Illustrates how to configure an object using closures in C#
class Program
{
static void Main(string[] args)
{
var obj1 = new ToBeConfigured(with =>
{
with.UseB();
with.SetParam("something");
});
Debug.Assert(obj1.Configuration.A == false);
Debug.Assert(obj1.Configuration.B == true);
Debug.Assert(obj1.Configuration.Param == "something");
Console.ReadKey();
}
}
class Configuration
{
public void UseA()
{
A = true;
}
public void UseB()
{
B = true;
}
public void SetParam(string data)
{
Param = data;
}
public bool A { get; private set; }
public bool B { get; private set; }
public string Param { get; private set; }
}
class ToBeConfigured
{
public ToBeConfigured(Action<Configuration> config)
{
var confInst = new Configuration();
config.Invoke(confInst);
Configuration = confInst;
}
public Configuration Configuration { get; private set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment