Skip to content

Instantly share code, notes, and snippets.

@PoisonousJohn
Last active February 20, 2018 18:00
Show Gist options
  • Save PoisonousJohn/b45cc7532a3f10466893f87a88f8e8a9 to your computer and use it in GitHub Desktop.
Save PoisonousJohn/b45cc7532a3f10466893f87a88f8e8a9 to your computer and use it in GitHub Desktop.
Reference Lazy<T> implementation for Unity
using System;
public class Lazy<T> {
public Lazy(Func<T> factory)
{
if (factory == null)
{
throw new ArgumentNullException("Lazy<T> doesn't accept null factory");
}
_factory = factory;
}
public T Value
{
get
{
if (_factory != null)
{
_value = _factory();
_factory = null;
}
return _value;
}
}
public bool IsValueCreated { get { return _factory == null; } }
private Func<T> _factory;
private T _value;
}
public static class Program
{
public static void Main()
{
var lazy = new Lazy<int>(() => new System.Random().Next(0, 100));
Console.WriteLine("Initialized: " + lazy.IsValueCreated);
var value = lazy.Value;
Console.WriteLine("Initialized: " + lazy.IsValueCreated);
Console.WriteLine("Value: " + lazy.Value + " == " + value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment