Search This Blog

Declaring variables in C#

 Variables declared this way within classes are called instance variables. They belong to an instance of the class.
Syntax
modifier dataType variableName; ///modifier is optional

///variables can be assigned values either separately or on declaration
variableName = value; ///separate line assignment

modifier dataType variableName = value; ///same line assignment

///implicitly typed variable
var variable2 = value;

Notes
The modifier (public, private) restricts or permits direct access to the variable with respect to its scope (class, method, etc.). Variables declared within a class are called fields.

Variables without a modifier are known as local variables, typically used within a method. They are temporary and only exist within the scope of the where its declared method.

dataType is the data type of the variable.

Example
public class Car { 
    private int speed; ///public variable declaration
    public int wheels; ///private variable declaration
    
    /*...constructor, etc...*/

    public void speedUp() {
        ///local variable declaration, in line assignment, only seen within speedUp method
        int speedIncrease = 10;
        speed += speedIncrease;
    }
}
Share:

No comments:

Blog Archive

Powered by Blogger.

Blog Archive

Recent Posts

Pages