This is so damn cool - I was amped when my coworker told our team about it - The Lazy<> class. It is a way of doing lazy instantiation of a singleton. There is finally a ‘right’ way to do singleton lazy instantiation in C#.

So here’s how you use it, in this example in a dead simple MVC Controller initializing and using a database. Here’s a bit of code from my little side project.

    public class HomeController : Controller
    {
        Lazy<SoundCloudContext> db = new Lazy<SoundCloudContext>();

        public ActionResult Index()
        {
            var tracks = db.Value.Tracks.ToList();
            IndexModel model = new IndexModel()
            {
                Tracks = tracks;
            };
            return View(tracks);
        }

How easy is that? No private variables or weird initalizer classes. The Lazy<> class also has methods for supporting thread safety and a delegate if you need to defer instantiation arguments. The only thing I don’t like is that you have to say db.Value instead of db to reference your actual object, but that’s really just nit picking.

#Update

I posted this to /r/csharp and some nice folks offered some good feedback. My code example wasn’t much of an example of the Singleton Pattern. The Lazy<> Class isn’t so much an implementation of that pattern more as a tool for implementing it. Moreover, Lazy<> is by default type safe, which I wasn’t clear about.

As this much more in-depth writeup at GeeksWithBlogs expalins, Lazy<> is a way to make sure your class isn’t instantiated until it is actually asked for (that’s why its lazy!) while avoiding a lot noisy code tricks.

So if you wanted to implement the singleton pattern using Lazy<> it might look something like this. (I basically ripped this code straight from that GeeksWithBlogs post by James Michael Hare He and everyone at GWB is a smarter and better coder than myself).

public class MyLazySingleton
{
	private static readonly Lazy<MySingleton> _instance = new Lazy<MyLazySingleton>(() => new MyLazySingleton());
    
    Private MyLazySingleton() {}
    
    public static MyLazySingleton Instance
    {
    	get
        {
        	return _instance.Value;
        }
    }
    
}

Now with this, you could statically ask for MyLazySingleton and always get the same single instance and be sure the class wasn’t initialized until the last possible moment.

Thanks again for the feedback, /r/csharp!