03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Variable Declaration Syntax ❘ 61<br />

Fields<br />

A variable that is declared at the class level, outside of any method, is called a field.<br />

Most developers recommend that you use properties instead of fields. Properties are<br />

described in the section “Properties” later in this chapter.<br />

The pieces of this declaration are<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤ ➤<br />

➤➤<br />

➤ ➤<br />

attributes—One or more attributes that specify extra properties for the variable. The following<br />

section, “Attributes,” describes attributes in more detail.<br />

accessibility—This determines which code can access the variable. The section<br />

“Accessibility” later in this chapter describes accessibility values in more detail.<br />

const—If you include this, the variable is a constant and its value cannot be changed later.<br />

Use the value to assign the constant a value.<br />

readonly—If you include this, the variable is similar to a constant except its value can be<br />

set either with a value clause or in the class’s constructor.<br />

static—This keyword indicates the variable is shared by all instances of the class.<br />

volatile—This keyword indicates the variable might be modified by code running in multiple<br />

threads running at the same time.<br />

type—The data type you want the variable to have.<br />

[]—Include empty square brackets [] to make an array.<br />

name—The name you want the variable to have.<br />

= value—The value you want the variable to initially have.<br />

For example, the following code defines a publically visible constant int variable named NumSquares<br />

and initializes it to the value 8.<br />

public const int NumSquares = 8;<br />

The section “Static, Constant, and Volatile Variables” later in this chapter provides more detail on<br />

the static, const, readonly, and volatile keywords.<br />

You can define and even initialize multiple variables of the same type in a single statement. The<br />

following statement declares and initializes two int variables.<br />

public int value1 = 10, value2 = 20;<br />

TIP Many developers prefer not to initialize multiple variables in the same statement<br />

to keep the code easier to read.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!