Why this division in class instantiation in C #?

1

In the book " Use the Head - C # , the author declares classes in a way that I did not understand their utility, according to example:

public partial class Form1 : Form 
{
    Farmer farmer;

    public Form1 () {
        InitializeComponent();
        farmer = new Farmer() { NumberOfCows = 15};
    }
}

I did not understand the difference in this declarative form and its division into two sentences, the two different locations, to simply declare:

Farmer farmer = new Farmer(){ NumberOfCows = 15};
    
asked by anonymous 30.01.2017 / 18:55

4 answers

4

You need to understand What is a builder for? . Read there and you will practically have your answer.

Now you wonder why it was not done outside the constructor, like this:

public partial class Form1 : Form {
    Farmer farmer = new Farmer { NumberOfCows = 15 };
    public Form1() {
        InitializeComponent();
    }
}

It's something that only the author of the code can explain. At least in this case. Maybe its intention was to show that you can declare the variable in the class and you can initialize it with a value in the constructor.

If this is it, it could be that hypothetically it might want to give the right order of initialization of each thing. As already said in the other question, the constructor is the only way you can control the boot order. In the way it was written the variable farmer starts with a null value and only after it passes the constructor does it generate a value. It might be a requirement of the Farmer class to do this, but nothing indicates.

It may have been done this way because later it will teach direct boot in the farmer field in the class without going through the constructor.

It may also be that the person who wrote this code does not know that they could always boot directly into the field or even in the property since C # 6. There is a lot of book that is written by those who do not master the technology. This line of books is written thinking about the cognition of the reader, I do not know if the more technical part has the same dedication that they give to the pedagogy.

I no longer like, for example, the fact of teaching to create a form called Form1 when maybe it should be a FarmerForm . The book seems to encourage programming addictions.

Notice that I pulled up the parentheses there at startup of the object. I'll tell you more about this in another question . If this is your question, read on to understand how this works.

To tell the truth I read this chapter of the book and found it confusing.

Understand that if the construction of the object in farmer depends on some parameter that comes from Form() then it would make sense to initialize in the constructor, after all it is the only way to parameterize its construction. But the Form class is not for constructor methods with parameters. She could, but she was not brought up thinking about it. It might not build the way you imagine if you build a parameterized constructor. So in my opinion it was done just for taste.

Now, if your doubt is because it does not do so:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        Farmer farmer = new Farmer { NumberOfCows = 15 };
    }
}

This would be wrong in this context. This way farmer is a local variable, so it would cease to exist at the end of the method execution. This has to do with scope and lifetime (read there to understand it better).

In this case, in theory, this variable should be used by all methods of the object created by Form1 . Again I do not much like the example. Because if it is to explain the concept of creating a field I think I should use a simpler class and not involve Form in it. If the intention is to teach using the Form class, and it does not seem to be the case, you should do it in a way that it has utility.

    
31.01.2017 / 03:45
2

Farmer farmer; does not instantiate anything. This only declares a variable of type Farmer .

The instance of this variable is done in the second example ( farmer = new Farmer() { NumberOfCows = 15 }; ).

Obviously I can not say why the author does this. It may be coding style, or it may actually have a plausible reason for it.

A good example would be that this variable will be used throughout the scope of form (as if it were global for form ), but needs to be instantiated only in the constructor call (which is exactly what happens in the example ) because some definition comes from "outside", that is, some validation is done with data coming from the caller of the form.

Given a simplistic example based on the question code, it would look like this:

Imagine that for some reason, there is a NumberOfTractors property that can only be defined within the Farmer class, ie it has set private.

The idea then is to get this value in the constructor, treat it and sett on the property.

public class Farmer
{
    public int NumberOfCows { get; set; }
    public int NumberOfTractors { get; private set; }

    public Farmer(int numberOfTractors)
    {
        AlgumaOperacaoQualquer(numberOfTractors);
        NumberOfTractors = numberOfTractors;
    }
}

public partial class Form1: Form
{
    Farmer farmer;

    public Form1(int nOfTractors)
    {            
        farmer = new Farmer(nOfTractors);
        /* Perceba que este valor é recebido pelo construtor de Form1. 
           E como só é possível enviar este parâmetro pelo construtor de 
           de Farm, então, a instanciação aqui se torna obrigatória */
    }
}
    
30.01.2017 / 19:05
2

On line:

Farmer farmer = new Farmer(){ NumberOfCows = 15};

means that the NumberOfCows attribute is being initialized, you can do this example:

Pessoa p = new Pessoa 
{
  Nome = "Gato",
  Idade = 25
}

It's a simple way to initialize properties without having to go directly to the constructor

new Pessoa("Gato", 25) 

and you can initialize the property you want.

Already the division

public partial class Form1 : Form {
    Farmer farmer;
}

It uses the partial command which is a way of dividing the class, usually used by code generators.

    
30.01.2017 / 19:04
1

In the above code, the author chose to instantiate the object Farmer farmer in the constructor:

public partial class Form1 : Form {
    Farmer farmer;
    public Form1 () {
        InitializeComponent();
        farmer = new Farmer() { NumberOfCows = 15};
    }
}

Another possible approach would be to instantiate the farmer object immediately upon object creation:

public partial class Form1 : Form {
    Farmer farmer = new Farmer() { NumberOfCows = 15};
    public Form1 () {
        InitializeComponent();
    }
}

Actually the behavior is basically the same, however it is customary to instantiate the objects inside the constructor, for a better organization.

    
30.01.2017 / 19:20