Appendix E
Operators

The C# operators fall into four main categories: arithmetic, comparison, logical, and bitwise. The following sections explain these categories and the operators they contain. The end of this appendix describes operator precedence and special operators, as well as operator overloading.

Arithmetic Operators

The following table lists the arithmetic operators provided by C#.

OperatorPurposeExampleResult
++Incrementx++ or ++xSets x = x + 1
--Decrementx-- or --xSets x = x - 1
Negation-xSets x = -x
+Unary plus+xSets x = +x (leaves x unchanged)
*Multiplication2 * 36
/Division3.0 / 21.5
%Modulus17 % 52
+Addition2 + 35
+Concatenation"Bob " + "Baker""Bob Baker"
-Subtraction3 - 21
<<Bit left shift10110111 << 101101110
>>Bit right shift10110111 >> 101011011

Comparison Operators

The following table lists the comparison operators provided by C#.

OperatorPurposeExampleResult
==EqualsA == Btrue if A equals B.
!=Not equalsA != Btrue if A does not equal B.
<Less thanA < Btrue if A is less than B.
<=Less than or equal toA <= Btrue if A is less than or equal to B.
>Greater thanA > Btrue if A is greater than B.
>=Greater than or equal toA >= Btrue if A is greater than or equal to B.
isObject is or inherits from a certain typeobj is Managertrue if obj is an object that inherits from Manager.

Logical Operators

The following table summarizes the C# logical operators.

OperatorPurposeExampleResult
!Negation!Atrue if A is false.
&AndA & Btrue if A and B are both true.
|OrA | Btrue if A or B or both are true.
^Xor (Exclusive Or)A ^ Btrue if A is true or B is true but both are not true.
&&And with short-circuit evaluationA && Btrue if A and B are both true.
||Or with short-circuit evaluationA || Btrue if A or B or both are true.

Bitwise Operators

Bitwise operators work much as logical operators do, except that they compare values 1 bit at a time. C# provides bitwise versions of the &, |, and ^ operators. It also provides ~, the bitwise negation operator.

Assignment Operators

Many operators have assignment versions. For example, the following code adds 10 to the value x and saves the result in variable x.

x += 10;

The complete list of assignment operators is: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, and >>=.

Conditional and Null-coalescing Operators

The conditional operator ?: (sometimes called the ternary operator) takes three operands. If the first operand is true, it returns the second operand. Otherwise it returns the third operand.

The null-coalescing operator ?? takes two operands. It returns its left operand if its value is not null. If the left operand is null, it returns its right operand.

Operator Precedence

The following table lists the operators in order of precedence. When evaluating an expression, the program evaluates an operator before it evaluates those in a lower section of the list.

OperatorDescription
( )Grouping (parentheses)
x++
x--
Post-increment
Post-decrement
+
-
!
~
++x
--x
(T)
Unary plus
Numeric negation
Logical negation
Bitwise negation
Pre-increment
Pre-decrement
Casting
*
/
%
Multiplication
Division
Modulus
+
+
-
Concatenation
Addition
Subtraction
<<
>>
Left shift
Right shift
<
>
<=
>=
is
Less than
Greater than
Less than or equal to
Greater than or equal to
Inherits from
==
!=
Equals
Does not equal
&Logical And
^Logical Xor
|Logical Or
&&Conditional And
||Conditional Or
??Null-coalescing
?:Conditional
=
+=
-=
...
Assignment operators

When operators are in the same section in the table, or if an expression contains more than one instance of the same operator, the program evaluates them in left-to-right order.

Use parentheses to change the order of evaluation and to make expressions easier to read.

DateTime and TimeSpan Operators

The DateTime and TimeSpan data types are related through their operators. The following list shows the relationships between these two data types.

  • DateTime − DateTime = TimeSpan
  • DateTime + TimeSpan = DateTime
  • TimeSpan + TimeSpan = TimeSpan
  • TimeSpan − TimeSpan = TimeSpan

The following table lists examples demonstrating convenient methods provided by the DateTime data type.

SyntaxMeaning
newDate = date1.Add(timespan1)Returns date1 plus timespan1
newDate = date1.AddYears(numYears)Returns date1 plus the indicated number of years
newDate = date1.AddMonths(numMonths)Returns date1 plus the indicated number of months
newDate = date1.AddDays(numDays)Returns date1 plus the indicated number of days
newDate = date1.AddHours(numHours)Returns date1 plus the indicated number of hours
newDate = date1.AddMinutes(numMinutes)Returns date1 plus the indicated number of minutes
newDate = date1.AddSeconds(numSeconds)Returns date1 plus the indicated number of seconds
newDate = date1.AddMilliseconds(numMilliseconds)Returns date1 plus the indicated number of milliseconds
newDate = date1.AddTicks(numTicks)Returns date1 plus the indicated number of ticks (100 nanosecond units)
newTimespan = date1.Subtract(date2)Returns the time span between date2 and date1
resultInt = date1.CompareTo(date2)Returns a value indicating whether date1 is greater than, less than, or equal to date2
resultBool = date1.Equals(date2)Returns true if date1 equals date2

Operator Overloading

To overload an operator, create a static method that returns the appropriate data type. Instead of giving the method a name, use the keyword operator followed by the operator symbol you want to overload. Next, define the parameters that the operator takes. Finally, write the code that the operator should execute.

For example, the following code defines a + operator for a simple Complex class.

public static Complex operator +(Complex operand1, Complex operand2)
{
    return new Complex()
    {
        Re = operand1.Re + operand2.Re,
        Im = operand1.Im + operand2.Im
    };
}

Unary operators that you can overload include: +, -, !, ~, ++, --, true, and false.

Binary operators that you can overload include: +, -, *, /, %, &, |, ^, <<, and >>. If you overload true, false 7, and |, the && and || operators are automatically overloaded for you.

Note that the second operand for the shift operators << and >> must be an int.

The assignment operators are automatically overloaded if you overload the corresponding operator. For example, if you overload *, then C# overloads *= for you.

See Chapter 5, “Operators,” for more information about overloading comparison, logical, and type conversion operators.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.146.139