mardi 4 septembre 2018

What's the correct way to have Singleton class in c#

I am learning Singleton design pattern in C#, and I have written below code in two ways, and I want to know Which one is the right way to create a Singleton class:

public sealed class TranslationHelper
{
    // first way
    private static readonly TranslationHelper translationHelper = new TranslationHelper();
    // second way
    public static readonly TranslationHelper translationHelpers = new TranslationHelper(); // Direct call

    public static TranslationHelper GetTranslationHelper()
    {
        return translationHelper;
    }

    private TranslationHelper()
    {
    }
}

CALL:

TranslationHelper instance = TranslationHelper.GetTranslationHelper();
TranslationHelper ins = TranslationHelper.translationHelpers;

Aucun commentaire:

Enregistrer un commentaire