Local Variables and their Scope

As we discovered in an earlier tutorial, statements are actions that are terminated with a semicolon. Statements can be also be nested.

A statement block is a collection of statements that run in order and are contained by curly braces.

Declarations

A declaration statement is where we declare a new variable. For example, we declare that there will be a new string with the identifier of “newString”. We can choose to initialise the new variable at this point but it isn’t required.

Additionally, we learnt earlier that constants are declared in the same manner, however, they can not be modified after they are declared and initialised.

Variable Scope

When you define a variable, it only exists within the current code block and no further unless explicitly defined. For example, if we had a method named “Double” and the variable “target” was defined within that code block, “target” cannot be seen from outside of this method. We refer to this as the scope of the variable.

You can only use a single identifier for one variable in a code block, you cannot assign multiple variables the same identifier.

Assignment Expressions

Assignment expressions are a type of statement that assigns a given value to a variable.


using System;

public class Program
{
	public static void Main()
	{
		int x; // Declaration
		x = 3; // Assignment expression
	}
}
                

Increment / Decrement Expressions

An increment expression is a type of statement that increments or decrements a value.


using System;

public class Program
{
	public static void Main()
	{
		int x;
		x = 3;
		x++; // Increment Expression
		x--; // Decrement Expression
	}
}
                

Method Call Expressions

A method call expression will call a method associated with the object. The method can either return a value, in which case it will be assigned to the variable on the left or, a method can be void which means that it will not return a value.


using System;

public class Program
{
	public static void Main()
	{
		Console.WriteLine("Hello World"); // Void method call expression

		string y = "new string";
		y = y.Insert(3, " insert"); // Non-void method call (assignment)
		Console.WriteLine(y);
	}
}
                

Object Instantiation Expression

An object instantiation expression is a call to the constructor of an object when it is created.


using System;
using System.Text;

public class Program
{
	public static void Main()
	{
		StringBuilder x = new StringBuilder(); // new StringBuilder() : object instantiation
	}
}
                
Car template (class) to object