Expressions


Now that you've seen how to declare and initialize variables, it's time to look at manipulating them. C# contains a number of operators for this purpose, including the = assignment operator you've used already. By combining operators with variables and literal values (together referred to as operands when used with operators), you can create expressions, which are the basic building blocks of computation.

The operators available range from the simple to the highly complex, some of which you might never encounter outside of mathematical applications. The simple ones include all the basic mathematical operations, such as the + operator to add two operands, and the complex ones include manipulations of variable content via the binary representation of this content. There are also logical operators specifically for dealing with Boolean values, and assignment operators such as =.

In this chapter, you concentrate on the mathematical and assignment operators, leaving the logical ones for the next chapter, where you examine Boolean logic in the context of controlling program flow.

Operators can be roughly classified into three categories:

  • Unary operators, which act on single operands

  • Binary operators, which act on two operands

  • Ternary operators, which act on three operands

Most operators fall into the binary category, with a few unary ones, and a single ternary one called the conditional operator (the conditional operator is a logical one, that is it returns a Boolean value; this is discussed in Chapter 4).

Let's start by looking at the mathematical operators, which span both unary and binary categories.

Mathematical Operators

There are five simple mathematical operators, two of which have binary and unary forms. In the next table, I've listed each of these operators, along with a quick example of its use and the results when it's used with simple numeric types (integer and floating point).

Operator

Category

Example Expression

Result

+

Binary

var1 = var2 + var3;

Var1 is assigned the value that is the sum of var2 and var3.

-

Binary

var1 = var2 - var3;

Var1 is assigned the value that is the value of var3 subtracted from the value of var2.

*

Binary

var1 = var2 * var3;

Var1 is assigned the value that is the product of var2 and var3.

/

Binary

var1 = var2 / var3;

Var1 is assigned the value that is the result of dividing var2 by var3.

%

Binary

var1 = var2 % var3;

Var1 is assigned the value that is the remainder when var2 is divided by var3.

+

Unary

var1 = +var2;

Var1 is assigned the value of var2.

-

Unary

var1 = -var2;

Var1 is assigned the value of var2 multiplied by –1.




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net