Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
17
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 2 Working with Variables, Operators, and Expressions

47

Declaring Implicitly Typed Local Variables

Earlier in this chapter, you saw that you declare a variable by specifying a data type and an identifier, like this:

int myInt;

It was also mentioned that you should assign a value to a variable before you attempt to use it. You can declare and initialize a variable in the same statement, like this:

int myInt = 99;

or even like this, assuming that myOtherInt is an initialized integer variable:

int myInt = myOtherInt * 99;

Now, remember that the value you assign to a variable must be of the same type as the variable. For example, you can assign an int value only to an int variable. The C# compiler can quickly work out the type of an expression used to initialize a variable and tell you if it does not match the type of the variable. You can also ask the C# compiler to infer the type of a variable from an expression and use this type when declaring the variable by using the var keyword in place of the type, like this:

var myVariable = 99;

var myOtherVariable = “Hello”;

Variables myVariable and myOtherVariable are referred to as implicitly typed variables.

The var keyword causes the compiler to deduce the type of the variables from the types of the expressions used to initialize them. In these examples, myVariable is an int, and myOtherVariable is a string. It is important to understand that this is a convenience for de-

claring variables only and that after a variable has been declared, you can assign only values of the inferred type to it—you cannot assign float, double, or string values to myVariable at

a later point in your program, for example. You should also understand that you can use the var keyword only when you supply an expression to initialize a variable. The following declaration is illegal and will cause a compilation error:

var yetAnotherVariable; // Error - compiler cannot infer type

Important If you have programmed with Visual Basic in the past, you may be familiar with the Variant type, which you can use to store any type of value in a variable. I emphasize here and

now that you should forget everything you ever learned when programming with Visual Basic about Variant variables. Although the keywords look similar, var and Variant mean totally differ-

ent things. When you declare a variable in C# using the var keyword, the type of values that you assign to the variable cannot change from that used to initialize the variable.

48 Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008

If you are a purist, you are probably gritting your teeth at this point and wondering why on earth the designers of a neat language such as C# should allow a feature such as var to creep in. After all, it sounds like an excuse for extreme laziness on the part of programmers and can make it more difficult to understand what a program is doing or track down bugs (and it can even easily introduce new bugs into your code). However, trust me that var has a very valid place in C#, as you will see when you work through many of the following chapters. However, for the time being, we will stick to using explicitly typed variables except for when implicit typing becomes a necessity.

If you want to continue to the next chapter

Keep Visual Studio 2008 running, and turn to Chapter 3.

If you want to exit Visual Studio 2008 now

On the File menu, click Exit. If you see a Save dialog box, click Yes (if you are using Visual Studio 2008) or click Save (if you are using Visual C# 2008 Express Edition) and save the project.

Chapter 2 Quick Reference

To

Do this

Declare a variable

Write the name of the data type, followed by the name of the

 

variable, followed by a semicolon. For example:

 

int outcome;

Change the value of a variable

Write the name of the variable on the left, followed by the

 

assignment operator, followed by the expression calculating the

 

new value, followed by a semicolon. For example:

 

outcome = 42;

Convert a string to an int

Call the System.Int32.Parse method. For example:

 

System.Int32.Parse(“42”);

Override precedence

Use parentheses in the expression to force the order of

 

evaluation. For example:

 

(3 + 4) * 5

Initialize several variables to the same value

Use an assignment statement that initializes all the variables. For example:

myInt4 = myInt3 = myInt2 = myInt = 10;

Increment or decrement a variable Use the ++ or -- operator. For example:

count++;

(Footnotes)

1 The value of 216 is 65,536; the value of 231 is 2,147,483,648; and the value of 263 is 9,223,372,036,854,775,808.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]