Working with partially constructed objects in .Net

June 28, 2010

Just a quick one, but what do you think will be the output of this program? It’s not what I expected:

class Program
{
	static void Main()
	{
		CanILeak leakyRef = null;

		try
		{
			new CanILeak(cil => leakyRef = cil);
		}
		catch (Exception)
		{
			Console.WriteLine("Exception");
		}

		if (leakyRef != null)
			leakyRef.AreYouStillThere();

		Console.ReadLine();
	}
}

class CanILeak
{
	public CanILeak(Action fail)
	{
		fail(this);
		throw new Exception();
	}

	public void AreYouStillThere()
	{
		Console.WriteLine("I'm still here");
	}
}

Discussion, links, and tweets

comments powered by Disqus

I'm a developer at Purplebricks and I sporadicaly tweet here. These posts in no way represent the views of my employeer.