Last active
February 20, 2018 18:00
-
-
Save PoisonousJohn/b45cc7532a3f10466893f87a88f8e8a9 to your computer and use it in GitHub Desktop.
Reference Lazy<T> implementation for Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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