Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Created November 14, 2018 11:38
Show Gist options
  • Save sangheestyle/696a6caf74504b8e3e77b2f774baedcd to your computer and use it in GitHub Desktop.
Save sangheestyle/696a6caf74504b8e3e77b2f774baedcd to your computer and use it in GitHub Desktop.
Practice closure in C#
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
</Project>
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Practice
{
public class GuardTask
{
public void Run(string first, string second, Action callback)
{
Console.WriteLine($"GuardTask:Run: {first}");
callback();
Console.WriteLine($"GuardTask:Run: {second}");
}
}
public static class TestHelpers
{
public static Action<Action> Subscribe(string first, string second)
{
return delegate (Action callback)
{
var guardTask = new GuardTask();
guardTask.Run(first, second, callback);
};
}
public static void WithCallback<T>(this Action<T> action, T callback)
=> action(callback);
public static Action SendEmails()
{
return delegate
{
Console.WriteLine("SendEmails: Callback!");
};
}
}
class Program
{
static void Main(string[] args)
{
TestHelpers.Subscribe("first", "second")
.WithCallback(TestHelpers.SendEmails());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment