Perform Lazy Object Initialization - CSharp Custom Type

CSharp examples for Custom Type:Object Initializer

Description

Perform Lazy Object Initialization

Demo Code


using System;// w  w w  .  ja  v  a2 s. c o  m
using System.Collections.Generic;
using System.Linq;
using System.Text;

class MainClass
    {
        static void Main(string[] args)
        {
            MyDataType eagerInstance = new MyDataType(false);
            Console.WriteLine("...do other things...");
            eagerInstance.sayHello();

            Lazy<MyDataType> lazyInstance = new Lazy<MyDataType>(() => new MyDataType(true));
            Console.WriteLine("...do other things...");
            lazyInstance.Value.sayHello();
        }
    }

    class MyDataType
    {
        public MyDataType(bool lazy)
        {
            Console.WriteLine("Initializing MyDataType - lazy instance: {0}", lazy);
        }

        public void sayHello()
        {
            Console.WriteLine("MyDataType Says Hello");
        }
    }

Result


Related Tutorials