# ResettableLazy<T>: a resettable version of .NET Lazy<T>

I implemented a resettable version of .NET Lazy (context: mostly to use it in a MemoryCache for auto refresh purposes on item expiration)

This is a very naive implementation and I am pretty sure there are couple of things that are not okay. In particular, I am not really sure whether the reset is fine. I think the assignment is atomic but I am not sure what can happen when there is an attempt to get the Value while it is resetting at the same (e.g. I am not sure whether the fact that the assignment is atomic is enough to guarantee proper operations).

public class ResettableLazy<T>
{
private Lazy<T> _lazy;

public bool IsValueCreated => _lazy.IsValueCreated;

public T Value => _lazy.Value;

{
_valueFactory = valueFactory;
}

{
}

public void Reset()
{
}
}


And played a bit around with:

public static class Program
{
public static void Main(params string[] args)
{
var lazy = new ResettableLazy<int>(() =>
{
return new Random().Next();
});

for (var i = 0; i < 1000; i++)
{
if (i % 2 == 0)
{
}

if (i % 3 == 0)
{
}
}

}
}


Is there any red flags in my implementation?

• It might be easier to cache the object that contains the Lazy<T>. When it expires you create a new one. IOW, the exact opposite of what you're doing. Instead of resetting Lazy so that it reads from the cache, cache the Lazy so that it expires. – Scott Hannen Dec 18 '17 at 20:47
• @ScottHannen or even better: create an interface and add a decorator like ExpirableLazy<T> taking a ResettableLazy<T> as a parameter. – t3chb0t Dec 21 '17 at 20:41
• @t3chb0t IExpirer<TLazy> where TLazy : ResettableLazy<ExpirableLazy<T>> – Scott Hannen Dec 21 '17 at 22:03
• @ScottHannen Actually I got various implementations to achieve my goal I thought the lazy fashion was interesting to explore. But yeah this is pretty much what I ended up doing. – Ehouarn Perret Dec 22 '17 at 13:41

One thing to note is that if Lazy<T>.IsValueCreated ever becomes true it stays true for the lifetime of the object, and this is not the case with your class. It's worth calling out that if the object is shared between threads than many of the reasons to use IsValueCreated become less reliable (e.g. accessing .Value may be expensive).