When should I instantiate a class?

3

I am doubtful when it is the best time to call instantiate a classe .

Should I do this in the beginning, before the constructor, in the constructor or at the time we are going to make use of any method?

In the example below I create instances of some classe and some Datatable , before my constructor:

public partial class Manutenção_cliente : DevExpress.XtraEditors.XtraForm
{
    consulta_bd consulta_bd = new consulta_bd();
    cadastro_bd cadastro_bd = new cadastro_bd();
    excluir_bd excluir_bd = new excluir_bd();
    controles_text control_text = new controles_text();
    DataTable cobranca = new DataTable();
    DataTable entrega = new DataTable();
    Consulta_cidade cidade = new Consulta_cidade();

    public int id_cliente, editar, chek_excluir, chek_new_cli, contador, id_end_cobranca, id_end_entrega, ck = 0, lad = 0;

    public Manutenção_cliente(int id)
    {
    
asked by anonymous 24.07.2016 / 15:34

1 answer

4

Classes are not called, only methods are called. At most it is calling the constructor that instantiates the class and the object is stored in the variable, usually in an indirect way.

If you are talking about where to declare the variables that will support the instance, there is no certain place pre-defined , is used where it has to use. It may be in the class, it may be within a method, if your lifetime should be local.

If you go at the beginning of the class, in the middle, at the end, before or after something, if everything goes scattered, little or nothing matters. It's a matter of organization and taste. It's very common to get it done early on, but not everyone follows it, and there may be cases where it's best to do it differently.

There is no technical requirement, the order can not be defined within the class, only within methods.

It is common to group all private members, then group the properties. It is also usual to group the static members. Some people like to use #region , but most prefer to avoid it.

If you need too much organization it is likely that the class is doing too many things.

In this case several variables of class Manutenção_cliente are being initialized when an instance of this class is created. It seems to be a wise decision for this case.

In some cases it may be that some members need to be initialized within the builder , common when you need a specific order or need to initialize other parts of the instances that can not be easily made into the variables (needs limb initialization), or some specific processing. In much rarer cases you may need to boot into some "normal" method, but this is a danger because the class will possibly be in an invalid state.

This code does not follow the C # naming pattern . It also uses public or at least internal memberships (default visibility), which should normally be avoided, but not at all costs , you need to know when to do it or not.

    
24.07.2016 / 16:02