Doubt in the method declaration

Asked

Viewed 62 times

3

Observe the following code:

 class Program
{
    int marks;
    static int maxmarx = 50;
    void CalcularPorcentagem()
    {
        int porcento = (this.marks * 100) / Program.maxmarx;

        Console.WriteLine(porcento);

    }

After testing the following two ways, I noticed that the program returns the same value when the class is instantiated. So I’d like to know the difference between using:

     int porcento = (this.marks * 100) / Program.maxmarx;

or

     int porcento = (this.marks * 100) / maxmarx;
  • Here is your answer: https://answall.com/questions/54012/qual-a-fun%C3%A7%C3%A3o-de-um-m%C3%A9todo-est%C3%A1tico

  • 3

    I believe that for this example there is no difference, but the first mode allows you to differentiate the class attribute from a local variable if there is a conflict of names in the scope. For example, if the local variable exists in this method int maxmarx = 1, the first mode will work perfectly, while the second will produce an "unexpected".

  • The second answer deals specifically with the subject addressed in this question. If you think not, let me know.

  • 1

    I would write var porcento = marks * 100 / maxmarx;, if the variable were used elsewhere, otherwise neither would exist.

  • So, Anderson, she mentions the value declared in the local variable of the Program class. If I need to reference the value 50, determined in the class creation, I use the Program. However, if I wish to use a value other than 50, I should call it without the Program., due to the value with which I want to work be different?

2 answers

1

You’re in the class Program referencing the static variable maxmarx; that is, within the class he sees the variable without having to reference the class.

So much so Program.maxmarx how much maxmarx have the same result.

1

So I’d like to know the difference between using

As it is shown, inside a code block (method) where there is no other variable called maxmarx, none.

Now, if you had a local variable called maxmarx, yes, to reference the static variable it is mandatory to reference using the class name (Program.maxmarx).


Outside of this scenario (local variable with the same name), referencing in the form presented or not at the discretion of the developer/development team.

It is the same discussion between referencing an instance variable with this or not. For example: this.marks * 100 or marks * 100? The result is the same.

Normally, this "type of Coding" is addressed/discussed at the beginning of the project by the development team, so that all developers work in the same way.

  • 1

    The correct is "you don’t have it" instead of "you don’t have it", because the "no" is classified as a próclise factor and has an attractive force over the pronoun. : x

  • @Andersoncarloswoss Raccoon, thanks. I’ll pack :P

Browser other questions tagged

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