C# Closure Constructors
I’ve been doing quite a lot of Javascript recently, one of the Javascript patterns I’ve been using extensively is Douglas Crockford’s closure based class construction. It just struck me today that you could do something similar in C#.
Here’s a cool cat:
public class Cat
{
protected Cat(){}
public static Cat New(string name)
{
return New(name, null);
}
public static Cat New(string name, Cat parent)
{
var self = new Cat();
self.GetParent = () => parent;
self.SayHello = () => "Hello, my name is " + name;
self.MakeKitten = kittenName => New(kittenName, self);
return self;
}
public Func<string> SayHello { get; protected set; }
public Func<Cat> GetParent { get; protected set; }
public Func<string, Cat> MakeKitten { get; protected set; }
}
Which you can use like this:
var cat = Cat.New("Timmy");
var kitten = cat.MakeKitten("Jenny");
Console.WriteLine(kitten.SayHello());
Console.WriteLine(kitten.GetParent().SayHello());
Which outputs:
Hello, my name is Jenny
Hello, my name is Timmy
The interesting thing is that you don’t have to declare any private class fields, all the state is encapsulated by the closures created in the constructor. It would be easy to define different Cat behaviours just by providing different implementations of SayHello, GetParent and MakeKitten at runtime.
What do you think? Could there be any benefits to creating classes like this? Obvious drawbacks?
Don’t take this too seriously, I’m not for a moment suggesting that you refactor your code.. just playing :)
0 comments