Why this division in the class instantiation in C#?

Asked

Viewed 110 times

1

In the book "Use the Head - C#", the author declares classes in a way that I did not understand their usefulness, according to the 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 the division of it into two sentences, the two different locations, of simply declaring:

Farmer farmer = new Farmer(){ NumberOfCows = 15};
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the tour how to do it, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

4 answers

4

You need to understand What good is a builder?. Read there and you’ll practically get your answer.

Now, if you want to know why it wasn’t made out of the builder, like this:

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

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

If so, it may be that, hypothetically, I wanted to give the right order to boot each thing. As already stated in the other question, the constructor is the only way you can control the boot order. How the variable was written farmer starts with a null value and only after passing the constructor does it generate a value. It may be that it would be a class requirement Farmer do this way, but nothing indicates.

It may be that it was done this way because later on it will teach to boot directly in the field farmer in the class without passing the constructor.

It may also be that the person who wrote this code does not know that he has always been able to boot directly into the field or even into 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 reader’s cognition, I don’t know if the more technical part has the same care that they give to pedagogy.

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

Note that I took even the parentheses there at the initialization of the object. I talk in more detail about the subject at another question. If that’s your question, read it to understand how it works.

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

Understand that if the construction of the object in farmer depend on some parameter that came 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 class Form is not to have constructor methods with parameters. You can, but it was not created with that in mind. It may not build the way you imagine if you create a constructor with parameters. So in my opinion it was made just for the sake of.

Now, if your doubt is why you don’t:

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

I put in the Github for future reference.

This would be wrong in that context. This way farmer is a local variable, so it would no longer exist at the end of the method execution. This has to do with life span and time (read there to better understand).

In this case, in theory, the variable should be used by all methods of the object created by Form1. Again, I don’t really like the example. Because if it’s to explain the concept of creating a field I think you should use a simpler class and not involve Form in this. If the intention is to teach use the class Form, and that doesn’t seem to be the case, you should do it in a way that he could use.

2

On the line:

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

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

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

It is a simple way to initialize properties without having to pass directly in the constructor

new Pessoa("Gato", 25) 

and you can initialize the property you want.

Already the division

public partial class Form1 : Form {
    Farmer farmer;
}

Use the command partial which is a way to divide the class, is usually used by code generators.

2

Farmer farmer; nonhaste nothing. This just 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’t tell you why the author does it. It may be encoding 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 to the form), but needs to be instantiated only in the call of the constructor (which is exactly what happens in the example) because some definition comes "from outside", ie, some validation is made with data coming from "Caller" form.


Giving a very simple example based on the code of the question, would be the following:

Imagine that for some reason, the property exists NumberOfTractors that can only be defined within the class Farmer, that is, she has the set private.

The idea then, is to receive this value in the builder, treat it and settar 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 */
    }
}

1

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

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 at the time of object creation:

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

In reality the behavior is basically the same, but it is customary to instantiate the objects inside the constructor, for a better organization.

  • 2

    the Farmer variable is being used at class level, so it is not being created and instantiated within the constructor. Your statement is wrong, since it is possible to instantiate the variable at the time of the statement. This is perfectly valid. public partial class Form1 : Form { Farmer farmer = new Farmer { NumberOfCows = 15 }}

  • @jbueno, my statement is about the current context of the code, in fact if the user wishes to instantiate the variable at the time of the declaration. he can do it perfectly. I only made a reflection as to the current context. I had misunderstood the question erroneously, I will edit it

Browser other questions tagged

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