Single instance of Class C #

3

I have a Windows Form with the following code:

public partial class frmCadastroPessoaFisica : Form
{
    public frmCadastroPessoaFisica()
    {
        InitializeComponent();
    }
}

I would like to create only one instance of this form.

Some answers on the subject in stackoverflow in English say to use the singleton pattern:

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
                lock (typeof(Singleton))
                    if (instance == null) instance = new Singleton();

            return instance;
        }
    }
}

source: linhadecodigo.com.br

Some say that using the singleton for this would be overzealous.

What is the right way to allow only one instance of this form?

    
asked by anonymous 15.07.2016 / 14:14

1 answer

6

There are several ways to ensure that only one instance of your class is invoked. Your example contains one of them, called singleton factory .

Another possibility is via static definition, as in the example below:

public static class Instances
{
    public static frmCadastroPessoaFisica frmCadastroPessoaFisica;

    static Instances()
    {
        frmCadastroPessoaFisica = new frmCadastroPessoaFisica();
    }
}

You can access the static instance via Instances.frmCadastroPessoaFisica .

    
15.07.2016 / 14:28