Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro C# Get Started C# Syntax C# Output C# Comments C# Variables C# Data Types C# Type Casting C# User Input C# Operators C# Math C# Strings C# Booleans C# If...Else C# Switch C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# Scope


Share

Variable Scope

In C#, a variable can only be used in the part of the program where it is created. This part is called the variable's scope.

Scope keeps variables apart. A variable in one method cannot be changed by another method by mistake, and different methods can use the same variable names.


Method Scope

A variable that is declared inside a method only exists inside that method. Other methods cannot use it:

Example

static void ShowScore()
{
  int score = 50;
  Console.WriteLine(score);
}

static void Main(string[] args)
{
  ShowScore();
  Console.WriteLine(score);  // Error
}

The compiler shows an error like this:

prog.cs(16,25): error CS0103: The name `score' does not exist in the current context

Try it Yourself »

The variable score belongs to ShowScore(). Main() cannot see it, so C# says that the name does not exist.

To get a value out of a method, use a return value.

Because each method has its own variables, different methods can use the same variable name. They are two different variables, and they do not affect each other:

Example

static void PlayerOne()
{
  int score = 10;
  Console.WriteLine("Player one: " + score);
}

static void PlayerTwo()
{
  int score = 20;
  Console.WriteLine("Player two: " + score);
}

static void Main(string[] args)
{
  PlayerOne();
  PlayerTwo();
}

Try it Yourself »



Block Scope

A block is the code between curly braces { }, for example the code inside an if statement or a loop.

A variable that is declared inside a block can only be used inside that block:

Example

int points = 80;

if (points > 50)
{
  string message = "You win!";
  Console.WriteLine(message);
}

Console.WriteLine(message);  // Error

The compiler shows an error like this:

prog.cs(17,25): error CS0103: The name `message' does not exist in the current context

Try it Yourself »

To use the variable after the block, declare it before the block. Inside the block, you only change its value:

Example

int points = 80;
string message = "Try again";

if (points > 50)
{
  message = "You win!";
}

Console.WriteLine(message);

Try it Yourself »

The same is true for loops. In for (int i = 0; i < 5; i++), the variable i can only be used inside the loop.


Variables in the Class

A variable that is declared in the class, outside the methods, can be used by all methods in the class:

Example

class Program
{
  static int score = 0;

  static void AddPoints()
  {
    score = score + 10;
  }

  static void Main(string[] args)
  {
    AddPoints();
    AddPoints();
    Console.WriteLine(score);  // 20
  }
}

Try it Yourself »

Both AddPoints() and Main() use the same score variable.

The variable needs the static keyword, just like the methods in Program. You will learn more about static in the Static chapter.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.