The Basic Operators in C

Team-Fly    

 
.NET and COM Interoperability Handbook, The
By Alan Gordon
Table of Contents
Chapter Four.  A Quick Introduction to C#


The Basic Operators in C#

The basic set of operators supported by the C# language is essentially the same as those supported by C and C++. You can group the available operators into the following categories: arithmetic, relational, logical assignment, and type operators. The conditional operator is in a category by itself.

Arithmetic Operators

Table 4-1 shows the list of available arithmetic operators.

Table 4-1. C# Arithmetic operators

Operator

Usage Example

Description

Unary Plus

res = +x;

Returns the value of x.

Unary Minus

res = -x

Returns zero minus x.

Addition

res = x + y

Adds x and y. Also used for string concatenation.

Subtraction

res=x - y

Subtracts y from x. When checked, will throw an OverflowException if the result is outside the range of the result type.

Multiplication

res=x*y

Multiplies y times x. When checked, will throw an OverflowException if the result is outside the range of the result type.

Division

res = x / y

Divides the x by x. Will throw a DivideByZeroException if y is zero.

Remainder

res = x % y

Returns the remainder of x/y. When checked, will throw a DivideByZeroException if y is zero.

Left shift

res = x << y;

Left shifts the bits in x by y positions . High-order bits are discarded, and empty, low-order bits are set to zero.

Right shift

res = x >> y;

Right shifts the bits in x by y positions. Low-order bits are discarded, and empty, high-order bits are set to zero.

Increment and Decrement (postfix)

res = x++

res = x

Increments (++) or decrements the () x by 1. The increment is performed after the read, so if x =2, res will equal 2 after res=x++.

Increment and Decrement (prefix)

res = ++x

res = x

Increments (++) or decrements the () x by 1. The increment is performed before the read, so, if x =2, res will equal 3 after res=x++.

Most of the arithmetic operators (the shift and increment/decrement operators are exceptions) are only defined for the int, uint, long, ulong, float, double, and decimal types. If you use one of these operators on a type smaller than int, like short or byte, the compiler will perform an implicit conversion to the int type. You will then receive a compiler error if you try to assign the result of the arithmetic operation, which is an int, to a byte or a short because the conversion from an int to a short or byte is a narrowing conversion that may cause data loss. In other words, the following code will not compile.

 short res, x=5, y=3;  // this code will not compile. Cannot res = x + y;   // implicitly convert type int to short. 

To compile this code, you must explicitly convert the result of the addition to a short as follows :

 short res, x=5, y=3; res = (short)(x + y); 

If you perform multiplication or addition on two large int values, the result will likely be too large to store in an int result. By default, the operation will overflow silently without throwing an exception. You can instruct the C# compiler to generate code that will throw an exception if it detects overflow using the /checked argument. The following command line causes the compiler to generate code that checks for overflow:

 csc /checked+ myfile.cs 

You do pay a slight performance penalty for this extra checking, which is probably why the default for both the C# command line and Visual Studio .NET is not to perform overflow checking.

Note

If you are using Visual Studio .NET, you can turn on overflow checking by changing the Checked for overflow setting from false (the default) to true on the property pages for your project (See chapter 5).


If you explicitly want to specify that you do not want overflow checking, you can use the following command line for the C# compiler:

 csc /checked- myfile.cs 

This is an unnecessary step, however, because overflow checking is off by default. Even if you have not enabled overflow checking globally using the compiler command-line switch, you can instruct the compiler to perform overflow checking for a particular set of operations using the checked operator as follows:

 checked {     int res, x=32000000, y=32000000;     res = x * y;    // this line will cause an exception             Console.WriteLine("res={0}",res); } 

Relational Operators

Table 4-2 lists the available relational operators in C#.

Table 4-2. C# Relational operators

Operator

Usage Example

Description

Equals

x == y

Returns true if x is equal to y.

Not Equals

x != y

Returns true if x is not equal to y.

Less than

x < y

Returns true if x is less than y.

Less than or equal

x <= y

Returns true if x is less than or equal to y.

Greater than

x > y

Returns true if x is greater than y.

Greater than or equal

x >= y

Returns true if x is greater than or equal to y.

These operators are straightforward and are exactly the same as the C/C++ relational operators, so I won't dwell on them.

Logical Operators

Table 4-3 lists the available logical operators in C#.

Table 4-3. C# Relational operators

Operator

Usage Example

Description

Bitwise AND

x & y

Returns the bitwise AND of x and y.

Bitwise OR

x y

Returns the bitwise OR of x and y.

Bitwise XOR

x ^ y

Returns the bitwise XOR of x and y.

Logical AND

x && y

Returns the logical AND of x and y.

Logical OR

x y

Returns the logical OR of x and y.

Logical negation

!(x [op] y)

Returns the negation of a Boolean expression.

Once again, these operators are straightforward and are exactly the same as the C/C++ relational operators, so I won't dwell on them.

Assignment Operators

C# uses a single equals (=) for assignment. Just like C and C++, C# also supports a variety of shortcut assignment operators that allow you to perform an operation on two operands and assign the result to the left operand. In all of these cases, you are essentially abbreviating the following statement:

 x = x [op] y 

as this:

 x [shortcut op] y 

In other words,

 x = x + y 

can be abbreviated to:

 x += y 

C# supports the following shortcut operations: +=, -=, *=, /=, &=, %=, ^=, >>=, <<=. I have already explained the long form of each of these operators, so I won't give a detailed explanation of each operator when used in the shortcut form.

Type Operators

C# supports three operators, typeof, is, and as, which deal with types instead of values.

TYPEOF

The typeof operator returns the System.Type object for a particular type. You can also get the System.Type object associated with a type by calling the GetType method on an instance of the type.

Note

The GetType method is implemented in the System.Object class, which is the root base class for all other types.


However, using the typeof operator, you can get the System.Type object without having to create an instance of the type. The following code uses the typeof operator to obtain the System.Type object associated with the Manager class and then prints out a list of the methods in the class:

 Type mgrType=  typeof  (Manager); foreach (MethodInfo method in mgrType.GetMethods()) {     Console.WriteLine(method.Name); } 
IS

You use the "is" operator to determine if an object reference can be converted to a specified type. For instance, if the Manager class is a subtype of an Employee class, a Manager object reference can be converted to an Employee object reference. However, an Employee object reference can only be converted to a Manager object reference if the Employee object reference actually points to a Manager object.

Note

If you are having problems understanding the last point, just remember that a Manager is an Employee, so you can always perform the conversion from Manager to Employee. However, all Employees are not Managers, so the conversion from Employee to Manager may not always work.


The "is" operator allows you to test if an Employee object can be converted to a Manager. The following code will print the bonus of the Manager because the empMgr, Employee object reference points to a Manager object.

 Employee empMgr=  new Manager(1,"Tamber Gordon",800,200);  if (empMgr  is  Manager) {     Manager mgr=(Manager)empMgr;     Console.WriteLine("Bonus = {0}",mgr.Bonus); } else       Console.WriteLine("Not a manager!"); 

The following code will print "Not a Manager!" because the empEmp, Employee object reference points to an Employee object:

 Employee empEmp=  new Employee(2,"Alan Gordon",500);  if (empEmp  is  Manager) {     Manager mgr=(Manager)empEmp;     Console.WriteLine("Bonus = {0}",mgr.Bonus); } else       Console.WriteLine("Not a manager!"); 
AS

The "as" operator tests to see if an object reference can be converted to a specified type just like the "is" operator. The difference is that the "as" operator also performs the conversion if it is valid. If the object reference cannot be converted to the specified type, the "as" operator returns null. The following code demonstrates how to use the "as" operator:

 Employee empMgr=new Manager(1,"Tamber Gordon",800,200); Manager mgr = empMgr  as  Manager; if (mgr != null)     Console.WriteLine("Bonus = {0}",mgr.Bonus); else       Console.WriteLine("Not a manager!"); 
THE CONDITIONAL OPERATOR

I'll end our discussion of C# operators by talking about the conditional operator, which doesn't fit neatly into any of our categories. The conditional operator selects from two expressions based on the result of a Boolean expression as follows:

 (boolean_exp) ? exp1 : exp2 

If the Boolean expression evaluates to true, the conditional operator will return the result of exp1; if the Boolean expression evaluates to false, the conditional operator will return the result of exp2. The following code demonstrates how to use the conditional operator:

 static string GetSalaryDescription(Manager mgr) {     return (mgr.Salary > 1000) ? "overpaid" : "underpaid"; } 

Team-Fly    
Top
 


. Net and COM Interoperability Handbook
The .NET and COM Interoperability Handbook (Integrated .Net)
ISBN: 013046130X
EAN: 2147483647
Year: 2002
Pages: 119
Authors: Alan Gordon

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