Turn every Class into a Singleton!


translation services usa

You can design any C# Class as a Singleton Class. By doing so you can not use it any other way.

Or you can design your Classes as Standard Classes and turn them with this Class into a Singleton:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
internal static class Singleton<T>
        where T : new()
{
    private static ConcurrentDictionary<Type, T> _instances =
        new ConcurrentDictionary<Type, T>();

    public static T Instance
    {
        get
        {
            return _instances.GetOrAdd(typeof(T), (t) => new T());
        }
    }
}

Then simply turn a normal Class into a Singleton via:

1
Singleton<MyClass>.Instance.MyMethodCall();





.

Leave a comment

Your email address will not be published. Required fields are marked *

Please answer the question in order to post. * Time limit is exhausted. Please reload CAPTCHA.