Operators


Although most of C#'s operators should be familiar to C and C++ developers, this section discusses the most important ones for the benefit of new programmers and Visual Basic converts, and to shed light on some of the changes introduced with C#.

C# supports the operators listed in the following table, although four (sizeof, *, ->, and &) are only available in unsafe code (code that bypasses C#'s type safety checking), which is discussed in Chapter 7, "Memory Management and Pointers":

Category

Operator

Arithmetic

+-*/%

Logical

&|^~&&||!

String concatenation

+

Increment and decrement

++ --

Bit shifting

<< >>

Comparison

== != <> <= >=

Assignment

=+=-=*=/=%=&=|=^=<<=>>=

Member access (for objects and structs)

.

Indexing (for arrays and indexers)

[]

Cast

()

Conditional (the Ternary Operator)

?:

Delegate concatenation and removal (discussed in Chapter 6, "Delegates and Events")

+-

Object Creation

new

Type information

sizeof (unsafe code only) is typeof as

Overflow exception control

checked unchecked

Indirection and Address

*->& (unsafe code only) []

Namespace alias qualifier (discussed in Chapter 2, "C# Basics")

::

Null coalescing operator

??

One of the biggest pitfalls to watch out for when using C# operators is that, like other C-style languages, C# uses different operators for assignment =, and comparison ==. For instance, the following statement means let x equal three:

 x = 3; 

If you now want to compare x to a value, you need to use the double equals sign ==:

 if (x == 3) 

Fortunately, C#'s strict type safety rules prevent the very common C error where assignment is performed instead of comparison in logical statements. This means that in C# the following statement will generate a compiler error:

 if (x = 3) 

Visual Basic programmers who are accustomed to using the ampersand (&) character to concatenate strings will have to make an adjustment. In C#, the plus sign (+) is used instead, whereas & denotes a bit-wise AND between two different integer values. | allows you to perform a bit-wise OR between two integers. Visual Basic programmers also might not recognize the modulus (%) arithmetic operator. This returns the remainder after division, so for example x%5 returns 2 if x is equal to 7.

You will use few pointers in C#, so you will use few indirection operators. Specifically, the only place you will use them is within blocks of unsafe code, because that's the only place in C# where pointers are allowed. Pointers and unsafe code are discussed in Chapter 7.

Operator Shortcuts

The following table shows the full list of shortcut assignment operators available in C#.

Shortcut Operator

Equivalent To

x++, ++x

x=x+1

x--, --x

x=x–1

x+=y

x=x+y

x-=y

x=x-y

x*=y

x=x*y

x/=y

x=x/y

x%=y

x=x%y

x>>= y

x=x>>y

x<<= y

x=x<<y

x&=y

x=x&y

x|=y

x=x|y

x^=y

x=x^y

You may be wondering why there are two examples each for the ++ increment and the -- decrement operators. Placing the operator before the expression is known as a prefix, and placing the operator after the expression is known as a postfix, and there is a difference in the way they behave.

The increment and decrement operators can act both as whole expressions and within expressions. When used by themselves the effect of both the prefix and postfix versions is identical and corresponds to the statement x=x+1. When used within larger expressions, the prefix operator will increment the value of x before the expression is evaluated; in other words, x is incremented and the new value is used in the expression. In contrast, the postfix operator increments the value of x after the expression is evaluated — the expression is evaluated using the original value of x. The following example uses the increment operator (++) as an example to demonstrate the difference between the prefix and postfix behavior:

 int x = 5; if (++x == 6) { Console.WriteLine("This will execute"); } if (x++ == 7) { Console.WriteLine("This won't"); } 

The first if condition evaluates to true, because x is incremented from 5 to 6 before the expression is evaluated. The condition in the second if statement is false, however, because x is incremented to 7 only after the entire expression has been evaluated (while x=6).

The prefix and postfix operators --x and x-- behave in the same way, but decrement rather than increment the operand.

The other shortcut operators, such as += and -=, require two operands, and are used to modify the value of the first operand by performing an arithmetic, logical, or bit-wise operation on it. For example, the next two lines are equivalent:

 x += 5;  x = x + 5; 

The Ternary Operator

The ternary operator (?:) is a shorthand form of the if...else construction. It gets its name from the fact that it involves three operands. It allows you to evaluate a condition, returning one value if that condition is true, or another value if it is false. The syntax is

 condition ? true_value : false_value 

Here, condition is the Boolean expression to be evaluated, true_value is the value that will be returned if condition is true, and false_value is the value that will be returned otherwise.

When used sparingly, the ternary operator can add a dash of terseness to your programs. It is especially handy for providing one of a couple of arguments to a function that is being invoked. You can use it to quickly convert a Boolean value to a string value of true or false. It is also handy for displaying the correct singular or plural form of a word, for example:

 int x = 1; string s = x.ToString() + " "; s += (x == 1 ? "man" : "men"); Console.WriteLine(s); 

This code displays 1 man if x is equal to one but will display the correct plural form for any other number. Note, however, that if your output needs to be localized to different languages, you will have to write more sophisticated routines to take account of the different grammatical rules of different languages.

The checked and unchecked Operators

Consider the following code:

 byte b = 255; b++; Console.WriteLine(b.ToString()); 

The byte data type can only hold values in the range zero to 255, so incrementing the value of b causes an overflow. How the CLR handles this depends on a number of issues, including compiler options, so whenever there's a risk of an unintentional overflow, you need some way of making sure that you get the result you want.

To do this, C# provides the checked and unchecked operators. If you mark a block of code as checked, the CLR will enforce overflow checking, and throw an OverflowException if an overflow occurs. Let's change the code to include the checked operator:

byte b = 255; checked { b++; } Console.WriteLine(b.ToString());

When you try to run this code, you will get an error message like this:

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.    at Wrox.ProCSharp.Basics.OverflowTest.Main(String[] args)



Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

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