Failed to display Address class fields when using object creation method expressed in C#

Asked

Viewed 76 times

3

Visual Studio 2017 suggested something that I was surprised, the creation of object without using the new operator, I was surprised, because I’m coming from Java and it’s been a year since I stopped and decided to go back to study.

Well, when creating a new Company object, it does not appear the fields of the Address class that are declared within the Company class, but within it also has the Plan class and this yes, appear in the complete.

I cannot see wrong, because the two classes are almost equal, apart from the fact that Plano receives inheritance from the Persistant class.

Below follows the code to see from the classes:

Business Class

namespace Cobranca.pkgModel
{
    public class Empresa : Persistant
    {
        private string nome;
        private string razaoSocial;
        private string cnpj;
        private string status;
        private Plano plano;
        private Endereco endereco;

        public Empresa()
        {
            Endereco = new Endereco();
            Plano = new Plano();
        }

        //métodos getter e setter
    }
}

Flat Class

namespace Cobranca.pkgModel
{

    public class Plano : Persistant 
    {
        private string nome;
        private string tipoCobranca;
        private double valor;

        //métodos getter e setter
    }
}

Address Class

namespace Cobranca.pkgModel
{
    public class Endereco
    {
        private string logradouro;
        private string numero;
        private string bairro;
        private string complemento;
        private string cep;
        private string cidade;
        private string estado;

        //métodos getter e setter
    }
}

Below follows the print I took from the screen

Print da tela ao tentar usar este recurso

Can anyone answer me why I’m going through this, since I created an equal method in class PlanoDAO and does not present this flaw.

And what name of this feature for me to study, that has to do with lambda?

Thank you


Answer:

Just for the record I edited my code as the confreres informed and it was like this:

            this.Model = new Empresa
            {
                Id = Convert.ToInt32(data["id"]),
                Nome = Convert.ToString(data["nome"]),
                RazaoSocial = Convert.ToString(data["razao_social"]),
                Cnpj = Convert.ToString(data["cnpj"]),
                Status = Convert.ToString(data["status"]),
            };

            this.Model.Plano = new Plano
            {
                Id = Convert.ToInt32(data["plano_pk"]),
                Nome = Convert.ToString(data["plano_nome"]),
                Valor = Convert.ToDouble(data["plano_valor"])
            };

            this.Model.Endereco = new Endereco
            {
                Logradouro = Convert.ToString(data["logradouro"]),
                Numero = Convert.ToString(data["numero"]),
                Bairro = Convert.ToString(data["bairro"]),
                Complemento = Convert.ToString(data["complemento"]),
                Cep = Convert.ToString(data["cep"]),
                Cidade = Convert.ToString(data["cidade"]),
                Estado = Convert.ToString(data["estado"])
            };

2 answers

5


This code should not be compiling:

public Empresa()
{
    Endereco = new Endereco();
    Plano = new Plano();
}

Note that you have declared the properties endereco and plano with the names completely on lowercase and how private, but here you are using the ones with the uppercase initial.

About the tiny

The is case-sensitive, then Plano1 is different from plano2.

1 - Refers to type Plano (the class declared)
2 - Refers to type property Plano whose name on this occurrence is plano

In the latest versions of Visual Studio, the highlight featured in the IDE reinforces the compiler’s interpretation of written code.

Observe :

empresa = new Empresa 
{
    Endereco. // AQUI
}

The word Addressee is in the color green (or blue, or greenish blue, or bluish green or whatever), in the same way as Empresa or MySqlCommand, for example. This suggests that at that time you are referencing the type, not the instance. Therefore, only static members of the class will be presented if they exist Endereco.

About the private

Even if you were using the name of the property correctly, you would not be able to assign the value of it, as it is in , the modifier private limits access to the property to the scope where it is declared (the class itself).

Solving

Then to correct it would be:

1 - Change the access modifiers of the fields in their classes to public, as in the example below:

public class Endereco
{
    public string logradouro;
    public string numero;
    public string bairro;
    public string complemento;
    public string cep;
    public string cidade;
    public string estado;
}

2 - Use the property instead of guy in builders:

var endereco = new Endereco
    {
        logradouro = "algum nome",
        numero = "22A",
        // ... por aí vai
    };

(...)the creation of object without using the new operator(...)

I think that your statement was the result of the confusion between guys and instances of the type. So by destroying the dreams, to create the instance of the kind you really need the new.

I hope I’ve helped.

  • 2

    I could be wrong, but I think the OP did not add in the question the getter and setter, see that you have a comment //getter and Setter methods, soon the Endereco = new Endereco(); compile

  • @Barbetta, in the class Empresa the property of type Endereco has the name endereco. Nowhere is a variable, field or property being declared with the name Endereco (With the initial capital). I don’t understand how getter / Setter would be related to this. Could you please clarify?

  • @Barbetta, I think I understand what you mean. Maybe he has the field and property declared in the class, where the property would have the same type name. If that’s the case, you’re right, compile. And my answer would be all based on the absence of that information.

  • I think he declared the getters and setters "the old fashioned", declaring a private variable, and below the getters and setters, Anyway, in my view your answer answers the question very well. + 1

  • @Barbetta on the first statement, yes, I did not add to not fill the question too much

  • @Diegorafaelsouza on the second post, I thought inside the body building the object Empresa, it would already automatically create the call to Endereco, I even thought about doing the two separately yes

  • @Barbetta on declaring getter and Setter the old-fashioned, what is the current fashion? Because I use the VS to help me in creating

  • @Diegorafaelsouza and @Barbetta, I will check here because I did it the old and less practical way, ie for example Empresa.Endereco.Logradouro = "valor";

  • @Macario1983 if the property has nothing else on get and set, the "current brand" would be public Endereco Endereco { get; set; }. Just this property without the private camp. But I based my answer on a possible confusion of understanding on your part (and possibly on mine, because part of the code was omitted - I can’t remember when I used the term getter or setter for the last time, it’s just propriedade or campo)

  • 1

    @Macario1983 It may be interesting you evaluate if it is not worth to pass as parameter of constructor Empresa an object Endereco filled out.

  • @Diegorafaelsouza I already instancio in the builder the objects Plano and Èndereco. But I can assess yes, only a doubt, this feature has some specific name?

  • 1

    @Not Macario1983. We call it propriedade autodeclarada (the one that doesn’t need a field private)

  • 2

    VS has a shortcut for property creation, in its class type prop and tighten TAB twice. If you write propfull and TAB twice, he creates her the "old-fashioned"

  • Gee, that’s nice @Barbetta, but they didn’t answer me, this way of creating object without using relatives on new, as it is called, it was VS himself who suggested me to reduce code.

  • 1

    @Macario1983, the constructor without parentheses is known as standard builder and alleviate the properties of the type at the time of instantiation we we call it initialization of the kind, This is one of several C facilitators#.

  • 1
  • 1

    @Diegorafaelsouza, it will be of great help these references, very dynamic the language.

Show 12 more comments

2

The right thing would be:

Endereco end = new Endereco()
{
    logradouro = "Rua teste",
    numero = "1200"
};

Without using the class name before the attribute (as you were doing).

However, there is a second problem, because all the properties of your classes are private.

When I add in VS Code, the following message appears:

'Endereco.logradouro' is Inaccessible due to its Protection level.

Switching to public would function and/or add the assignment of values to some method, such as the constructor. The choice depends on the purpose of the class and its properties. If it is just a container, switch to public. However, if it is a necessity for the data to be populated in the instance creation, use the constructor.

[...]but inside it also has the Plan class and this yes, appear in the complete.

Since it is not in the examples where it is being created, I cannot affirm the differences. If it is being declared within the same scope of its class, no errors will occur.

  • Friend, I omitted the get and set statements from the code not to lengthen too much, but put a comment if you notice.

  • 1

    @Macario1983 yes, that’s true. But, the way it was implementing imply in the above mentioned corrections to make it work.

Browser other questions tagged

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