C# Programming/Operators

From Wikibooks, open books for an open world
Jump to: navigation, search

C# operators and their precedence closely resemble the operators in other languages of the C family.

Similar to C++, classes can overload most operators, defining or redefining the behavior of the operators in contexts where the first argument of that operator is an instance of that class, but doing so is often discouraged for clarity.

Operators can be grouped by their arity as unary, binary.

Following are the built-in behaviors of C# operators.

Arithmetic[edit]

The following arithmetic operators operate on numeric operands (arguments a and b in the "sample usage" below).

Sample usage Read Type Explanation
a + b a plus b binary + returns the sum of its arguments.
a - b a minus b binary - returns the difference between its arguments.
a*b a times b binary * returns the multiplicative product of its arguments.
a/b a divided by b binary / returns the quotient of its arguments. If both of its operators are integers, it obtains that quotient using integer division (i.e. it drops any resulting remainder).
a%b a mod b binary % operates only on integer arguments. It returns the remainder of integer division of those arguments. (See modular arithmetic.)
a++ a plus plus or Postincrement a unary ++ operates only on arguments that have an l-value. When placed after its argument, it increments that argument by 1 and returns the value of that argument before it was incremented.
++a plus plus a or Preincrement a unary ++ operates only on arguments that have an l-value. When placed before its argument, it increments that argument by 1 and returns the resulting value.
a-- a minus minus or Postdecrement a unary -- operates only on arguments that have an l-value. When placed after its argument, it decrements that argument by 1 and returns the value of that argument before it was decremented.
--a minus minus a or Predecrement a unary -- operates only on arguments that have an l-value. When placed before its argument, it decrements that argument by 1 and returns the resulting value.

Logical[edit]

The following logical operators operate on boolean or integral operands, as noted.

Sample usage Read Type Explanation
a&b a bitwise and b binary & evaluates both of its operands and returns the logical conjunction ("AND") of their results. If the operands are integral, the logical conjunction is performed bitwise.
a&&b a and b binary && operates on boolean operands only. It evaluates its first operand. If the result is false, it returns false. Otherwise, it evaluates and returns the results of the second operand. Note that, if evaluating the second operand would hypothetically have no side effects, the results are identical to the logical conjunction performed by the & operator. This is an example of Short Circuit Evaluation.
a | b a bitwise or b binary | evaluates both of its operands and returns the logical disjunction ("OR") of their results. If the operands are integral, the logical disjunction is performed bitwise.
a || b a or b binary || operates on boolean operands only. It evaluates the first operand. If the result is true, it returns true. Otherwise, it evaluates and returns the results of the second operand. Note that, if evaluating the second operand would hypothetically have no side effects, the results are identical to the logical disjunction performed by the | operator. This is an example of Short Circuit Evaluation.
a ^ b a x-or b binary ^ returns the exclusive or ("XOR") of their results. If the operands are integral, the exclusive or is performed bitwise.
!a not a unary ! operates on a boolean operand only. It evaluates its operand and returns the negation ("NOT") of the result. That is, it returns true if a evaluates to false and it returns false if a evaluates to true.
~a bitwise not a unary ~ operates on integral operands only. It evaluates its operand and returns the bitwise negation of the result. That is, ~a returns a value where each bit is the negation of the corresponding bit in the result of evaluating a.

Bitwise shifting[edit]

Sample usage Read Type Explanation
a << b a left shift b binary << evaluates its operands and returns the resulting first argument left-shifted by the number of bits specified by the second argument. It discards high-order bits that shift beyond the size of its first argument and sets new low-order bits to zero.
a >> b a right shift b binary >> evaluates its operands and returns the resulting first argument right-shifted by the number of bits specified by the second argument. It discards low-order bits that are shifted beyond the size of its first argument and sets new high-order bits to the sign bit of the first argument, or to zero if the first argument is unsigned.

Relational[edit]

The binary relational operators ==, !=, <, >, <=, and >= are used for relational operations and for type comparisons.

Sample usage Read Explanation
a == b a is equal to b For arguments of value type, the operator == returns true, if its operands have the same value, false otherwise. For the string type, it returns true, if the strings' character sequences match. For other reference types (types derived from System.Object), however, a == b returns true only if a and b reference the same object.
a != b a is not equal to b The operator != returns the logical negation of the operator ==. Thus, it returns true, if a is not equal to b, and false, if they are equal.
a < b a is less than b The operator < operates on integral types. It returns true, if a is less than b, false otherwise.
a > b a is greater than b The operator > operates on integral types. It returns true, if a is greater than b, false otherwise.
a <= b a is less than or equal to b The operator <= operates on integral types. It returns true, if a is less than or equal to b, false otherwise.
a >= b a is greater than or equal to b The operator >= operates on integral types. It returns true, if a is greater than or equal to b, false otherwise.

Assignment[edit]

The assignment operators are binary. The most basic is the operator =. Not surprisingly, it assigns the value (or reference) of its second argument to its first argument.

(More technically, the operator = requires for its first (left) argument an expression to which a value can be assigned (an l-value) and for its second (right) argument an expression that can be evaluated (an r-value). That requirement of an assignable expression to its left and a bound expression to its right is the origin of the terms l-value and r-value.)

The first argument of the assignment operator (=) is typically a variable. When that argument has a value type, the assignment operation changes the argument's underlying value. When the first argument is a reference type, the assignment operation changes the reference, so the first argument typically just refers to a different object, but the object that it originally referenced does not change (except that it may no longer be referenced and may thus be a candidate for garbage collection).

Sample usage Read Explanation
a = b a equals (or set to) b The operator = evaluates its second argument and then assigns the results to (the l-value indicated by) its first argument.
a = b = c b set to c, and then a set to b Equivalent to a = (b = c). When there are consecutive assignments, the right-most assignment is evaluated first, proceeding from right to left. In this example, both variables a and b have the value of c.

Short-hand Assignment[edit]

The short-hand assignment operators shortens the common assignment operation of a = a operator b into a operator= b, resulting in less typing and neater syntax.

Sample usage Read Explanation
a += b a plus equals (or increment by) b Equivalent to a = a + b.
a -= b a minus equals (or decrement by) b Equivalent to a = a - b.
a *= b a multiply equals (or multiplied by) b Equivalent to a = a*b.
a /= b a divide equals (or divided by) b Equivalent to a = a/b.
a %= b a mod equals b Equivalent to a = a%b.
a &= b a and equals b Equivalent to a = a&b.
a |= b a or equals b Equivalent to a = a|b.
a ^= b a xor equals b Equivalent to a = a^b.
a <<= b a left-shift equals b Equivalent to a = a << b.
a >>= b a right-shift equals b Equivalent to a = a >> b.

Type information[edit]

Expression Explanation
x is T returns true, if the variable x of base class type stores an object of derived class type T, or, if x is of type T. Else returns false.
x as T returns (T)x (x cast to T), if the variable x of base class type stores an object of derived class type T, or, if x is of type T. Else returns null. Equivalent to x is T ? (T)x : null
sizeof(x) returns the size of the value type x. Remarks: The sizeof operator can be applied only to value types, not reference types..
typeof(T) returns a System.Type object describing the type. T must be the name of the type, and not a variable. Use the GetType method to retrieve run-time type information of variables.

Pointer manipulation[edit]

NOTE: Most C# developers agree that direct manipulation and use of pointers is not recommended in C#. The language has many built-in classes to allow you to do almost any operation you want. C# was built with memory-management in mind and the creation and use of pointers is greatly disruptive to this end. This speaks to the declaration of pointers and the use of pointer notation, not arrays. In fact, a program may only be compiled in "unsafe mode", if it uses pointers.

Expression Explanation
*a Indirection operator. Allows access the object being pointed.
a->member Similar to the . operator. Allows access to members of classes and structs being pointed.
a[] Used to index a pointer.
&a References the address of the pointer.
stackalloc allocates memory on the stack.
fixed Temporarily fixes a variable in order that its address may be found.

Overflow exception control[edit]

Expression Explanation
checked(a) uses overflow checking on value a
unchecked(a) avoids overflow checking on value a

Others[edit]

Expression Explanation
a.b accesses member b of type or namespace a
a[b] the value of index b in a
(a)b casts the value b to type a
new a creates an object of type a
a + b if a and b are strings, concatenates a and b. If any addend is null, the empty string is used instead. If one addend is a string and the other one is a non-string object, ToString() is called on that object before concatenation.
a + b if a and b are delegates, performs delegate concatenation
a ? b : c if a is true, returns the value of b, otherwise c
a ?? b if a is null, returns b, otherwise returns a
@"a" verbatim text, i.e., escape characters are ignored