Lesson 13

Understanding Scope

A variable's scope is the code that can “see” or access that variable. It determines whether a piece of code can read the variable's value and give it a new value.

In this lesson you learn what scope is. You learn why restricting scope is a good thing and how to determine a variable's scope.

Scope within a Class

A C# class (and note that Form types are classes, too) contains three main kinds of scope: class scope, method scope, and block scope. (If you have trouble remembering what a class is, review Lesson 9's section “Understanding Classes and Instances.”)

Variables with class scope are declared inside the class but outside of any of its methods. These variables are visible to all of the code throughout the instance of the class and are known as fields.

Variables with method scope are declared within a method. They are usable by all of the code that follows the declaration within that method.

Variables with block scope are declared inside a block defined by curly braces {} nested inside a method. The section “Block Scope” later in this lesson says more about this.

For example, consider the following code that defines the form's constructor (Form1), a field, and some variables inside event handlers:

namespace VariableScope { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // A field. int a = 1; private void clickMeButton_Click(object sender, EventArgs e) { // A method variable. int b = 2; MessageBox.Show("a = " ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.