Skip to content

Instantly share code, notes, and snippets.

@JayBazuzi
Created June 9, 2022 20:47
Show Gist options
  • Save JayBazuzi/2fab0f078e9ebcb82125a4859d063895 to your computer and use it in GitHub Desktop.
Save JayBazuzi/2fab0f078e9ebcb82125a4859d063895 to your computer and use it in GitHub Desktop.
[TestClass]
public class Tests
{
[TestMethod]
public void TestProgram()
{
foreach (var main in new[] {
DirectCall.Program.Main1,
DependencyInjection.Program.Main2,
EventBased.Program.Main3,
EventBased.Program.Main4,
})
{
using var output = new StringWriter();
Console.SetOut(output);
main();
Assert.AreEqual("Hello, World!", output.ToString());
}
}
[TestMethod]
public void TestConfigure()
{
var (aClass, foo) = EventBased.Program.Configure();
Assert.AreEqual(
foo.Bar,
aClass.OnBar?.GetInvocationList().Single()
);
}
}
namespace DirectCall
{
class Foo { public void Bar(string message) { Console.Write(message); } }
class AClass
{
private readonly Foo _foo = new Foo();
public void Do()
{
this._foo.Bar("Hello, World!");
}
}
static class Program
{
public static void Main1()
{
var aClass = new AClass();
aClass.Do();
}
}
}
namespace DependencyInjection
{
internal interface IFoo
{
void Bar(string message);
}
class Foo : IFoo { public void Bar(string message) { Console.Write(message); } }
class AClass
{
private readonly IFoo _foo;
public AClass(IFoo foo)
{
this._foo = foo;
}
public void Do()
{
this._foo.Bar("Hello, World!");
}
}
static class Program
{
public static void Main2()
{
var aClass = new AClass(new Foo());
aClass.Do();
}
}
}
namespace EventBased
{
class Foo { public void Bar(string message) { Console.Write(message); } }
class AClass
{
public Action<string>? OnBar;
public void Do()
{
this.OnBar?.Invoke("Hello, World!");
}
}
static class Program
{
public static void Main3()
{
var foo = new Foo();
var aClass = new AClass();
aClass.OnBar += foo.Bar;
aClass.Do();
}
public static (AClass, Foo) Configure()
{
var foo = new Foo();
var aClass = new AClass();
aClass.OnBar += foo.Bar;
return (aClass, foo);
}
public static void Main4()
{
var (foo, aClass) = Configure();
foo.Do();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment