4.2. Defining Variables

Some programmers see a statement like

int val;

and think that the program is defining or declaring a variable named val. Many programmers use the terms define and declare interchangeably. Those programmers are wrong. Defining a variable is very different from declaring a variable. Let's see why the two terms are actually quite different.

4.2.1. Defining a Variable from the Compiler's Point of View

Suppose you write the statement

int i;

in a program. In your mind, you are simply telling the program that you wish to create an integer variable named i for use in your program. To Visual Studio, however, things aren't quite that simple. Let's see what Visual Studio has to do just to process this simple statement.

4.2.1.1. Step One: Preliminary Syntax Checking

First, Visual Studio must check the statement for syntax errors. A syntax error occurs anytime you write a program statement that does not obey C# syntax rules. For example, you know that a variable name cannot begin with a digit character or contain punctuation characters. If you tried to create a variable with either of these conditions, Visual Studio would issue an error message. You learned in Chapter 3 that if you make a syntax error in a program statement, Intellisense places a squiggly line under the offending statement. Because we know the syntax of our program statement is correct, there is no squiggly line and Visual Studio moves to the next step.

4.2.1.2. Step Two: Symbol Table Checking

Get Beginning C# 3.0 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.