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

Asked

Viewed 1,085 times

-4

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

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

6

What is a variable?

instance variable

This variable belongs to the object, concretely it only exists when the object is created. In the class it only serves as a plan for how to create the object. In all instance methods you can access it because it internally 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 cannot be accessed by the class or otherwise, it has to say which object you want the variable from.

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

class variable

These are variables that exist throughout the life 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. Then we can understand that there is a unique object in memory with class variables. These variables are shared throughout the application (unless they are private).

class Exemplo {
    public static int total;
}

automatic variable (local variable)

Are the variables of the methods, usually present in the stack (may be in the register). They have their lifespan automatically managed while the method is running. They’re called automatics so.

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.

variable of static duration

Same as class variable.

I put in the Github for future reference.

Browser other questions tagged

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