What is a local variable and where can it be declared in C#?

Experience Level: Junior
Tags: C#

Answer

In C#, local variable is a variable that is declared within a method. Such variable is then visible to and accessible from the rest of the code that is below the variable declaration. If you declare a local variable inside of a nested block statement, then this variable will be visible to and accessible from the rest of the code that is below the variable declaraion but only in the same or other nesed block statement.

Example
public class Program 
{
  public static void Main() 
  {
		var myFirstVariable = 1;
		
		// The variable myFirstVariable will be accessible here
		if (myFirstVariable >= 1) 
       {
		  var mySecondVariable = 15;

		  // The variable myFirstVariable will be accessible here,
		  // because it was declare in parent block statement and
		  // the current block statement is nested in this statement.
		  
		  // The variable mySecondVariable will be accessible here.
		  
		}
		
		// The variable myFirstVariable will be accessible here
 
        // The variable mySecondVariable won't be accessible here,
		// because it was declared in a different block statement
		// and we are already outside of it.

  }
}

Other C# job interview questions
C# for beginners
C# for beginners

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself