What is a lazy instance

Is a lazy instance about using smaller code, but getting the same result? Of course, this is usually a good thing (ensuring that the code is short / efficient does not impair readability / maintainability).

Please refer to this lazy instance:

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
} 

No private property Instance(I know this is implicit) - is this what makes it lazy - is it a fact that we don’t have the customization facility in the property public static Singleton Instance?

+5
source share
5 answers

Suppose we have a type field that is expensive to build

class Foo
{
    public readonly Expensive expensive = new Expensive();
    ...
}

, instansiating Foo instansiating Expensive - , - Expensive. :

class Foo
{
    Expensive _expensive;
    public Expensive
    {
        get
        {
            if (_expensive == null) _expensive = new Expensive();
            return _expensive;
        }
    }
    ...
}

instansiation.

+11

- , , .

, .

Wikipedia ( ).

+6

, -, .

instance , . , new.

+5

, Singleton .

+2

, .

. msdn Lazy Initialization

singleton , . , , .

+2
source

All Articles