Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>Lazy&lt;T&gt;</code> (<a href="http://msdn.microsoft.com/en-us/library/dd642331.aspx">MSDN</a>) is a generic wrapper which allows creating an instance of <code>T</code> on demand by holding a <code>T</code> factory method (<code>Func&lt;T&gt;</code>) and calling it when <code>Vaue</code> property getter is accessed. </p> <p><code>LazyInitializer</code> - static class with a set of static methods, this is just a helper which uses <a href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx">Activator.CreateInstance()</a> (reflection) able to instantiate a given type instance. It does not keep any local private fields and does not expose any properties, so no memory usage overheads. </p> <p>Worth noting that both classes uses <code>Func&lt;T&gt;</code> as instance factory.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.threading.lazyinitializer.aspx">MSDN</a> says in few words about <code>LazyInitializer</code> class:</p> <blockquote> <p>These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using references to ensure targets have been initialized as they are accessed.</p> </blockquote> <p>PS: I found interesting a way how <code>LazyIntiializer</code> checks whether instance already initialized, it just compare a passed in reference to a <code>default(T)</code>, nice:</p> <pre><code>private static T EnsureInitializedCore&lt;T&gt;(ref T target, Func&lt;T&gt; valueFactory) where T : class { T t = valueFactory(); if (t == null) { throw new InvalidOperationException(Environment.GetResourceString("Lazy_StaticInit_InvalidOperation")); } Interlocked.CompareExchange&lt;T&gt;(ref target, t, default(T)); return target; } </code></pre> <p>What seems strange to me, it creates a new instance each time before an actual check:</p> <pre><code>T t = valueFactory(); // ... and only then does check </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload