Wednesday, November 19, 2014

Lazy

Introduction


Lazy <T> is the wrapper class for lazy initialization of an object that provides lazy initialization for the class or user defined type.  Lazy initialization of an object is used when you want to defer the creation of an object until it's actually used.  This could be quite useful if you have a dependent object that isn't used until more extensive operations are required to be completed but your object has to exist.

In layman's terms: you don't have to create the object early on in your coding and potentially call it later.

Coding


Onto a sample.  Let's create a class called Dalek that only writes out the phrase we've all heard: Ex-ter-min-ate!.  But we only want to do this when the object is actually used.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LazyTSample
{
  class Program
  {
    static void Main(string[] args)
    {
      Lazy<Dalek> lazyDalek = new Lazy<Dalek>();
      Console.WriteLine("Dalek is created : " + lazyDalek.IsValueCreated + "\n");
      Dalek drWhoEnemy = lazyDalek.Value;
      Console.WriteLine("\nDalek value has been set : " + lazyDalek.IsValueCreated);

      Console.WriteLine("\nPress Any Key to Exit.");
      Console.ReadKey();
    }
  }

  public class Dalek
  {
    public Dalek()
    {
      Console.WriteLine("EX-TER-MIN-ATE!");
    }
  }
}


Output
















Huzzah!  Coding sample works, this should be quite useful for more beefier operations to finish creation before your object needs to be used if it's ever called.

Source(s):


No comments:

Post a Comment