Detect singleton

CSharp · Console

/Program.cs

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

namespace Example
{
    class Component {}

	class MySingleton : Component
    {
        static public MySingleton Instance = null;
    }

    class MyMistake : Component
    {
        public MyMistake Instance = null;
    }

    static class ExtensionMethods
    {
		public static bool TrySet_SingletonInstance<T>(this T c) where T : Component
		{
			var target = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public).SingleOrDefault(p => p.FieldType == typeof(T));
			if (target == null) return false;
			var oldValue = (T)target.GetValue(null);
			if (oldValue != null) return false;
			target.SetValue(null, c);
			return true;
		}
    }

    public class Program
    {
        static public void Main()
        {
            var singleton = new MySingleton();
            var ok = singleton.TrySet_SingletonInstance();
            Console.WriteLine(ok);

            var mistake = new MyMistake();
            var oops = mistake.TrySet_SingletonInstance();
            Console.WriteLine(oops);
        }
    }
}
;