Advertisement
fcamuso

Singleton - classe base

Jan 4th, 2021
655
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.62 KB | None | 0 0
  1. using System;
  2.  
  3. namespace SingletonEasy
  4. {
  5.   class MyClass
  6.   {
  7.     static private MyClass instance = null;
  8.     static public MyClass Instance
  9.     {
  10.       get
  11.       {
  12.         //if (instance == null) instance = new MyClass();
  13.         //return instance;
  14.         return instance ??= new MyClass(); //null-coalescing
  15.       }
  16.     }
  17.  
  18.     public void Metodo() { Console.WriteLine("metodo richiamato"); }
  19.  
  20.     private MyClass() { Console.WriteLine("Oggetto creato"); }
  21.   }
  22.  
  23.   class Program
  24.   {
  25.     static void Main(string[] args)
  26.     {
  27.       MyClass.Instance.Metodo();
  28.       MyClass.Instance.Metodo();
  29.     }
  30.   }
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement