More thoughts on Lazy

Something that I missed when I mentioned my thoughts on an implementation of Lazy<T>, was that Microsoft was already a couple of steps ahead of me, and will include their own version in .NET 4.0, the MSDN documentation is here.

Their approach is slightly different to mine. Something I tried to do with my implementation was allow you to treat the Lazy<T> as the same type as the generic parameter, by adding the two implicit conversion operators and overriding the equals and hash methods. Microsoft has gone for a slightly different approach by making it immutable, and requiring you call the .Value property to get at the data.

It’d be interesting to hear why Microsoft went for this approach, but I can only guess they felt it was important to see that you’re dealing with an Lazy<T>, I prefer the approach closer to Nullable<T>, where the getting of the value is partially abstracted away.

There’s a couple more differences to mine, including optional thread safety, serialization and a better debugging experience with various debugger attributes, which I’d definitely do in my implementation next time around. Though does the optional thread safety really provide that much of a benefit?

Moving forward, I think there’s value in having this be a first level language construct, much like Nullable is, wouldn’t it be awesome to have:

    int~ fileCount = Directory.GetFiles(".").Length;

Compile into this?

    Lazy<int> fileCount = new Lazy<int>(() => Directory.GetFiles(".").Length);

Comments are closed.