Working with Variables, Operators, and Expressions in Microsoft Visual C#
- 12/15/2012
After completing this chapter, you will be able to
Understand statements, identifiers, and keywords.
Use variables to store information.
Work with primitive data types.
Use arithmetic operators such as the plus sign (+) and the minus sign (–).
Increment and decrement variables.
In Chapter 1, “Welcome to C#,” you learned how to use the Microsoft Visual Studio 2012 programming environment to build and run a console program and a graphical application. This chapter introduces you to the elements of Microsoft Visual C# syntax and semantics, including statements, keywords, and identifiers. You’ll study the primitive types that are built into the C# language and the characteristics of the values that each type holds. You’ll also see how to declare and use local variables (variables that exist only in a method or other small section of code), learn about the arithmetic operators that C# provides, find out how to use operators to manipulate values, and learn how to control expressions containing two or more operators.
Understanding Statements
A statement is a command that performs an action, such as calculating a value and storing the result, or displaying a message to a user. You combine statements to create methods. You’ll learn more about methods in Chapter 3, “Writing Methods and Applying Scope,” but for now, think of a method as a named sequence of statements. Main, which was introduced in the previous chapter, is an example of a method.
Statements in C# follow a well-defined set of rules describing their format and construction. These rules are collectively known as syntax. (In contrast, the specification of what statements do is collectively known as semantics.) One of the simplest and most important C# syntax rules states that you must terminate all statements with a semicolon. For example, you saw in Chapter 1 that without its terminating semicolon, the following statement won’t compile:
Console.WriteLine("Hello World!");
The trick to programming well in any language is learning the syntax and semantics of the language and then using the language in a natural and idiomatic way. This approach makes your programs more easily maintainable. As you progress through this book, you’ll see examples of the most important C# statements.