Writing C# Expressions
Source: C# Unleashed
Chapter 3: Writing C#Expressions
In This Chapter
- Unary Operators
- Binary Operators
- The Ternary Operator
- Other Operators
- Enumeration Expressions
- Array Expressions
- Statements
- Blocks
- Labels
- Declarations
- Operator Precedence and Associativity
C# provides a complete set of language elements for writing expressions.An expression is a set of language elements combined to perform a meaningfulcomputation. This chapter provides guidance in building C# expressions.
This chapter demonstrates expressions created with each of C#’s built-inoperators. All aspects of operators are covered in order to provide anunderstanding of their effects.
There are four types of operators—unary, binary, ternary, and a fewothers that don’t fit into a category. Unary operators affect a singleexpression. Binary operators require two expressions to produce a result. Theternary operator has three expressions. The others can only be explained byreading each of their descriptions.
For C++ and Java Programmers
C#operators and their precedence are the same. No surprises here at all. Ifdesired, you could skip this section without missing anything.
Unary Operators
As previously stated, unary operators affect a single expression. In manyinstances, the unary operators enable operations with simpler syntax than acomparable binary operation. The unary operators include + (plus),- (minus), ++ (increment), -- (decrement), !(logical negation), and ~ (bitwise complement).
Note
Mathematical operations onfloating-point types are performed according to IEEE 754 arithmetic.
The Plus Operator
The plus operator (+) has no effect on the expression it’s usedwith. Why would a language have an operator that has no effect? For consistency.Most C# operators have a logical complement. Since there is a minus operator,its logical complement is the plus operator. The + operator isavailable to explicitly document code. Here are a couple examples:
int negative = -1;
int positive = 1;
int result;
result = +negative; // result = -1
result = +positive; // result = 1
The Minus Operator
The minus operator (-) allows negation of a variable’s value.In integer and decimal types, the result is the number subtracted from zero. Forfloating-point types, the - operator inverts the sign of the number.When a value is NaN (not a number), the result is still NaN.Here are some examples:
int negInt = -1;
decimal posDec = 1;
float negFlt = -1.1f;
double nanDbl = Double.NaN;
int resInt;
decimal resDec;
float resFlt;
double resDbl;
resInt = -negInt; // resInt = 1
resDec = -posDec; // resDec = -1
resFlt = -negFlt; // resFlt = 1.1
resDbl = -nanDbl; // resDbl = NaN
The Increment Operator
The increment operator (++) allows incrementing the value of avariable by 1. The timing of the effect of this operator depends upon which sideof the expression it’s on.
Here’s a post-increment example:
int count;
int index = 6;
count = index++; // count = 6, index = 7
In this example, the ++ operator comes after the expressionindex. That’s why it’s called a post-increment operator. Theassignment takes place and then index is incremented. Since theassignment occurs first, the value of index is placed intocount, making it equal 6. Then index is incremented to become7.
Here’s an example of a pre-increment operator:
int count;
int index = 6;
count = ++index; // count = 7, index = 7
This time the ++ operator comes before the expressionindex. This is why it’s called the pre-increment operator.Index is incremented before the assignment occurs. Since indexis incremented first, its value becomes 7. Next, the assignment occurs to makethe value of count equal 7.
The Decrement Operator
The decrement operator (--) allows decrementing the value of avariable. The timing of the effect of this operator again depends upon whichside of the expression it is on. Here’s a post-decrement example:
int count;
int index = 6;
count = index–; // count = 6, index = 5
In this example, the -- operator comes after the expressionindex, and that’s why it’s called a post-decrement operator.The assignment takes place and then index is decremented. Since theassignment occurs first, the value of index is placed intocount, making it equal 6. Then index is decremented to become5.
Here’s an example of a pre-decrement operator:
int count;
int index = 6;
count = –index; // count = 5, index = 5
This time the -- operator comes before the expressionindex, which is why it’s called the pre-decrement operator.Index is decremented before the assignment occurs. Since indexis decremented first, its value becomes 5, and then the assignment occurs tomake the value of count equal 5.
The Logical Complement Operator
A logical complement operator (!) serves to invert the result of aBoolean expression. The Boolean expression evaluating to true will befalse. Likewise, the Boolean expression evaluating to falsewill be true. Here are a couple examples:
bool bexpr = true;
bool bresult = !bexpr; // bresult = false
bresult = !bresult; // bresult = true
The Bitwise Complement Operator
A bitwise complement operator (~) inverts the binary representationof an expression. All 1 bits are turned to 0. Likew
ise, all
0 bits are turned to1. Here’s an example:
byte bitComp = 15; // bitComp = 15 = 00001111b
byte bresult = (byte) ~bitComp; // bresult = 240 = 11110000b
Binary Operators
Binary operators are those operators that work with two operands. Forexample, a common binary expression would be a + b—the additionoperator (+) surrounded by two operands. The binary operators arefurther subdivided into arithmetic, relational, logical, and assignmentoperators.
Arithmetic Operators
This is the first group of binary operators, those supporting arithmeticexpressions. Arithmetic expressions are composed of two expressions with anarithmetic operator between them. This includes all the typical mathematicaloperators as expected in algebra.
The Multiplication Operator
The multiplication operator (*) evaluates two expressions andreturns their product. Here’s an example:
int expr1 = 3;
int expr2 = 7;
int product;
product = expr1 * expr2; // product = 21
The Division Operator
The division operator (/), as its name indicates, performsmathematical division. It takes a dividend expression and divides it by adivisor expression to produce a quotient. Here’s an example:
int dividend = 45;
int divisor = 5;
int quotient;
quotient = dividend / divisor; // quotient = 9
Notice the use of integers in this expression. Had the result been afractional number, it would have been truncated to produce the integerresult.
The Remainder Operator
The remainder operator (%) returns the remainder of a divisionoperation between a dividend and divisor. A common use of this operator is tocreate equations that produce a remainder that falls within a specified range.Here’s an example:
int dividend = 33;
int divisor = 10;
int remainder;
remainder = dividend % divisor; // remainder = 3
No matter what, as long as the divisor stays at 10, the remainder will alwaysbe between 0 and 9.
The Addition Operator
The addition operator (+) performs standard mathematical addition byadding one number to another. Here’s an example:
int one = 1;
int two;
two = one + one; // two = 2
The Subtraction Operator
The subtraction operator (-) performs standard mathematicalsubtraction by subtracting the value of one expression from another. Here’san example:
decimal debt = 537.50m;
decimal payment = 250.00m;
decimal balance;
balance = debt – payment; // balance = 287.50
The Left Shift Operator
To shift the bits of a number to the left, use the left shift operator(<<). The effect of this operation is that all bits move to theleft a specified number of times. High-order bits are lost. Lower order bits arezero filled. This operator may be used on the int, uint, long, and ulong datatypes. Here’s an example.
uint intMax = 4294967295; // 11111111111111111111111111111111b
uint byteMask;
byteMask = intMax << 8; // 11111111111111111111111100000000b
The Right Shift Operator
The right shift operator (>>) shifts the bits of a number tothe right. By providing a number to operate on and the number of digits, everybit shifts to the right by the number of digits specified. Only use the rightshift operator on int, uint, long, and ulongdata types. The uint, ulong, positive int, andpositive long types shift zeros from the left. The negativeint and negative long types keep a 1 in the sign bitposition and fill the next position to the right with a 0. Here aresome examples:
uint intMax = 4294967295; // 11111111111111111111111111111111b
uint shortMask;
shortMask = intMax >> 16; // 00000000000000001111111111111111b
int intMax = -1; // 11111111111111111111111111111111b
int shortMask;
shortMask = intMax >> 16; // 10000000000000001111111111111111b
For Java Programmers
C# doesn’thave a right shift with zero extension operator (>>>).
Relational Operators
Relational operators are used to make a comparison between two expressions.The primary difference between relational operators and arithmetic operators isthat relational operators return a bool type rather than a number. Anotherdifference is that arithmetic operators are applicable to certain C# typeswhereas relational operators can be used on every possible C# type, whetherbuilt-in or not. Floating-point types are evaluated according to IEEE 754. Theresults of a relational expression are either true orfalse.
The Equal Operator
To see if two expressions are the same, use the equal operator (==).The equal operator works the same for integral, floating-point, decimal, andenum types. It simply compares the two expressions and returns a bool result.Here’s an example:
bool bresult;
decimal debit = 1500.00m;
decimal credit = 1395.50m;
bresult = debit == credit; // bresult = false
When comparing floating-point types, +0.0 and –0.0 areconsidered equal. If either floating-point number is NaN (not a number), equalreturns false.
The Not Equal Operator
The not equal operator (!=) is the opposite of the equal operatorfor all types, with a slight variation for floating-point types only. If one ofthe floating-point numbers is NAN (not a number), not equal returns true.
There are two forms of not equal applicable to expressions. The first is thenormal not equal operator (!=). The other is a negation of the equaloperator !(a==b). Normally, these two forms always evaluate to the samevalue. The exception occurs when evaluating floating-point expressions where oneor both expressions evaluate to NaN and the relational operator in the negationof an expression is <, >, &
lt;=, or>=. The a > b form evaluates to false, but the!(a<=b) evaluates to true. Here are some examples:
bool bresult;
decimal debit = 1500.00m;
decimal credit = 1395.50m;
bresult = debit != credit; // bresult = true
bresult = !(debit == credit); // bresult = true
The Less Than Operator
If it’s necessary to find out if one value is smaller than another, usethe less than operator (<). The expression on the left is beingevaluated and the expression on the right is the basis of comparison. When theexpression on the left is a lower value than the expression on the right, theresult is true. Otherwise, the result is false. Here’s anexample:
short redBeads = 2;
short whiteBeads = 23;
bool bresult;
bresult = redBeads < whiteBeads; // bresult=true, work harder
The Greater Than Operator
If it’s necessary to know that a certain value is larger than another,use the greater than operator (>). It compares the expression on theleft to the basis expression on the right. When the expression on the left is ahigher value than the expression on the right, the result is true.Otherwise, the result is false. Here’s an example:
short redBeads = 13;
short whiteBeads = 12;
bool bresult;
bresult = redBeads > whiteBeads; // bresult=true, good job!
The Less Than or Equal Operator
Sometimes it’s necessary to know if a number is either lower than orequal to another number. That’s what the less than or equal operator(<=) is for. The expression on the left is compared to the expression on theright. When the expression on the left is either the same value as or less thanthe one on the right, less than or equal returns true. This operator isthe opposite of the greater than operator, which means that !(a>b)would produce the same results. The exception is when there’s afloating-point expression evaluating to NaN, in which case the result is alwaystrue. Here’s an example of the less than or equal operator:
float limit = 4.0f;
float currValue = 3.86724f;
bool Bresult;
bresult = currValue <= limit; // bresult = true
The Greater Than or Equal Operator
As its name implies, the greater than or equal operator (>=)checks a value to see if it’s greater than or equal to another. When theexpression to the left of the operator is the same as or more than theexpression on the right, greater than or equal returns true. Thegreater than or equal operator is the opposite of the less than operator.Here’s an example:
double rightAngle = 90.0d;
double myAngle = 96.0d;
bool isAbtuse;
isAbtuse = myAngle >= rightAngle; // Yes, myAngle is abtuse
Logical Operators
Logical operators perform Boolean logic on two expressions. There are threetypes of logical operators in C#: bitwise, Boolean, and conditional.
Continues…
Pages: 1 2












No comments yet... Be the first to leave a reply!