What is the difference between class instance variables, automatic (local) and static duration?

-4

What's the difference between these variable types? How to identify them? How does C # work with them?

    
asked by anonymous 23.11.2017 / 22:12

1 answer

6

What is a variable?

  

instance variable

This variable belongs to the object, specifically it only exists when the object is created. In the class it serves only as a plan of how to create the object. In all instance methods you can access it because internally it has a parameter ( this ) in all instance methods since they receive the object (usually by reference) without you seeing.

They can only be accessed through an object. It can not be accessed by the class or otherwise, it has to say of which object you want the variable.

class Exemplo {
    private int valor;
    public string nome;
}
  

class variable

They are variables that exist throughout the lifetime of the application, they are accessed through the class because there is only one of it, it is not like objects that can have several. So we can understand that there is a unique object in memory with class variables. These variables are shared by the entire application (unless they are private).

class Exemplo {
    public static int total;
}
  

auto variable (local variable)

They are the method variables, usually present in the stack (it can be in the register). They have their managed life time automatically while the method is running. They are called automatics for this.

class Exemplo {
    public static int total;
    private int valor;
    public string nome;
    public string Metodo(int parametro) => (total + valor + parametro).ToString() + nome;
}

Note that parameters are local variables, the difference is only the initialization that is made in the method call.

  

static duration variable

Same as class variable.

I placed GitHub for future reference.

    
23.11.2017 / 22:29