GrayMP

Lazy singleton demo

May 21st, 2018
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.85 KB | None | 0 0
  1. using System;
  2.  
  3. namespace ConsoleApp4
  4. {
  5.     class Program
  6.     {
  7.         public class LazyItem
  8.         {
  9.             public readonly string foobar;
  10.  
  11.             public LazyItem(string foobar)
  12.             {
  13.                 this.foobar = foobar;
  14.             }
  15.         }
  16.         public class LazyContainer
  17.         {
  18.             private readonly Lazy<LazyItem> common;
  19.             public LazyContainer()
  20.             {
  21.                 common = new Lazy<LazyItem>(() => new LazyItem("common"));
  22.             }
  23.             public LazyItem Common => common.Value;
  24.         }
  25.  
  26.         // https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx
  27.         static void Main(string[] args)
  28.         {
  29.             var c1 = new LazyContainer();
  30.             Assert(c1.Common, c1.Common); // ok
  31.  
  32.             var c2 = new LazyContainer();
  33.             Assert(c1.Common, c2.Common); // not ok
  34.         }
  35.  
  36.         public static void Assert(object o, object o2)
  37.         {
  38.             if (o.GetHashCode() != o2.GetHashCode())
  39.             {
  40.                 throw new Exception();
  41.             }
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment