Single instance C#Class

Asked

Viewed 258 times

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 say to use the Singleton standard:

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

Already others say that using Singleton for this would be exaggeration.

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

  • My question is in the case of Forms or GUI-type classes, I believe that this question that has been cited is more in the broad and generic sense.

  • All right, thanks for your attention.

  • Just see if you really need one form or only the data that fills it.

  • I consider Singleton an antipattern these days, but I think in certain situations it’s not worth adding a DI and control technique to ensure these problems... so if it’s a functional solution that doesn’t cause so many disorders, here is a great link explaining various ways to implement Singleton and the advantage/disadvantage of each: http://csharpindepth.com/Articles/General/Singleton.aspx

  • @Thiagolunardi is only the form, the application is large and the form can be "called" from several places, but only one instance of it can exist at a time.

  • Singleton Pattern is considered bad: https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons

Show 1 more comment

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.

  • I hadn’t thought about it, I’m gonna do a test here.

  • If you’re going to create statically, I think you could start the value of the variable in its own definition. Just remembering that in these ways the creation of the form is always carried out, even when it is not used...

  • @Gabrielkatakura In fact the instance is created when first mentioned in the code, Gabriel. Feel free to test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.