Skip to content

Instantly share code, notes, and snippets.

@vatbub
Created December 25, 2018 22:51
Show Gist options
  • Save vatbub/f4e63985f10ed0ecc2923b89f4418f9d to your computer and use it in GitHub Desktop.
Save vatbub/f4e63985f10ed0ecc2923b89f4418f9d to your computer and use it in GitHub Desktop.
A Singleton superclass in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace SingletonDemo
{
public class Program
{
public static void Main(string[] args)
{
SampleClass.Instance.Test();
}
}
public class Singleton<TSubclass> where TSubclass:Singleton<TSubclass>, new() // das new zwingt die Subklasse, einen parameterlosen Konstruktor zu haben
{
private static TSubclass _instance;
public static TSubclass Instance
{
get
{
if (_instance == null)
_instance = new TSubclass();
return _instance;
}
}
}
public class SampleClass : Singleton<SampleClass>
{
public void Test()
{
Console.WriteLine("Hello world from the singleton");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment