Make global reference in C#

Asked

Viewed 343 times

1

I am creating a simple database-free operations system in C#. It has 3 forms, being them: Login.Cs, Cadastro.Cs and Main.Cs. Also has the class Account.Cs, where operations are carried out.

My question is this: no form Register.Cs I created a reference called mconta and I would like it to be global. In this case only the Cadastro.Cs has access to it.

Conta[] mconta;
mconta = new Conta[10];
  • Almost always this is wrong.

1 answer

2

There are several ways to do this, including a pattern called Singleton that could meet depending on your case, I will put only one way, simple, but I think it gets "messy" then I would have to see how is your code, your organization, anyway...

In the Account class itself, set a variable to public static:

public class Conta
{
    //Declare sua variável:
    public static Conta[] mConta = new Conta[10];
}

In any other class, you can access it only by class name:

... Conta.mConta;

But I recommend you review your need, I don’t think that’s necessary. Another issue is to use generic collections instead of array, it is much simpler and practical:

List<Conta> mConta = new List<Conta>();
  • In the first code should not create as public static class Conta ?

  • It depends on the need... If it is a static class, or a static variable, in my example I use a variable, ie an instance of the class

Browser other questions tagged

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