< C Sharp Programming

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 nullary, unary, binary, ternary, n-ary.

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

Arithmetic

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

ExpressionReadArityExplanation
a + ba plus bbinary+ returns the sum of its arguments.
a - ba minus bbinary- returns the difference between its arguments.
a*ba times bbinary* returns the multiplicative product of its arguments.
a/ba divided by bbinary/ 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%ba mod bbinary% operates only on integer arguments. It returns the remainder of integer division of those arguments. (See modular arithmetic.)
a++a plus plus or Postincrement aunary++ 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.
++aplus plus a or Preincrement aunary++ 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 aunary-- 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.
--aminus minus a or Predecrement aunary-- 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

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

ExpressionReadArityExplanation
a&ba bitwise and bbinary& 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&&ba and bbinary&& 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 | ba bitwise or bbinary| 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 || ba or bbinary || 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 ^ ba x-or bbinary^ returns the exclusive or ("XOR") of their results. If the operands are integral, the exclusive or is performed bitwise.
!anot aunary! 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.
~abitwise not aunary~ 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

ExpressionReadArityExplanation
a << ba left shift bbinary<< 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 >> ba right shift bbinary>> 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

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

ExpressionReadArityExplanation
a == ba is equal to bbinaryFor 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 != ba is not equal to bbinaryThe 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 < ba is less than bbinaryThe operator < operates on integral types. It returns true, if a is less than b, false otherwise.
a > ba is greater than bbinaryThe operator > operates on integral types. It returns true, if a is greater than b, false otherwise.
a <= ba is less than or equal to bbinaryThe operator <= operates on integral types. It returns true, if a is less than or equal to b, false otherwise.
a >= ba is greater than or equal to bbinaryThe operator >= operates on integral types. It returns true, if a is greater than or equal to b, false otherwise.

Assignment

The most basic is the operator =. Not surprisingly, it assigns the value (or reference) of its second argument to its first argument. As such, the assignment operator is binary, but has an n-ary form.

(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).

ExpressionReadArityExplanation
a = ba equals (or set to) bbinaryThe operator = evaluates its second argument and then assigns the results to (the l-value indicated by) its first argument.
a = b = cb set to c, and then a set to bn-aryEquivalent 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. This may be continued ad infinitum to assign the same r-value to multiple l-values (e.g., a = b = c = d = 0; is equivalent to a = 0; b = 0; c = 0; d = 0;).

Short-hand Assignment

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.

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

Type information

ExpressionReadArityExplanation
x is Tis x of type Tbinaryreturns 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 Tcast x to Tbinaryreturns (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)size of xunaryreturns the size of the value type x. Remarks: The sizeof operator can be applied only to value types, not reference types..
typeof(T)type of Tunaryreturns 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

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.

ExpressionReadArityExplanation
*aobject at aunaryIndirection operator. Allows access the object being pointed.
a->membermember member of abinarySimilar to the . operator. Allows access to members of classes and structs being pointed.
a[b]object at offset b from abinaryUsed to index a pointer.
&areference to aunaryReferences the address of the pointer.
stackalloc aallocate a on the stackbinaryAllocates memory on the stack, rather than the heap. See C Sharp Programming/Keywords/stackalloc.
fixed aprevent a from being relocatedbinaryTemporarily fixes a variable in order that its address may be found. See C Sharp Programming/Keywords/fixed.

Overflow exception control

ExpressionReadArityExplanation
checked(a)evaluate a and check for overflowunaryuses overflow checking on value a. See C Sharp Programming/Keywords/checked.
unchecked(a)evaluate a without checking for overflowunaryavoids overflow checking on value a. See C Sharp Programming/Keywords/unchecked.

Others

ExpressionReadArityExplanation
a.bmember b of abinaryAccesses member b of type or namespace a. If b is a field, it calls the get function for that field.
a[b]item b in abinaryReturns the value of index b in a. Arrays use 0-origin indexing.
(a)bcast b to type abinaryExplicitly casts the value b to type a. Type b must have a cast function that casts directly to a or to another type that has a cast function to a.
new acreate a new an-aryCreates an object of type a and calls its default constructor. Type a may include constructors with arguments, in which case it takes the form new a(type1 arg1, type2 arg2, ...). See C Sharp Programming/Keywords/new.
a + bconcatenate string b to the end of string abinaryIf 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 + bconcatenate delegate b to delegate abinaryIf a and b are delegates, performs delegate concatenation.
a ? b : cif a then b else cternaryIf a is true, evaluates and returns the value of b, otherwise it evaluates and returns c. Only one of b and c will be evaluated.
a ?? bif a is null then b else abinaryIf a is null, evaluates and returns the value of b, otherwise evaluates and returns a. If a is non-null, b will not be evaluated.
a?.bif a is not null then evaluate bbinaryThis determines if an object is null before attempting to reference a member field or method. Ternary use in conjunction with ?? to provide an alternative (e.g. a?.b()??c). Can be used in n-ary form with ?[] for continual null-checks (e.g., a?.b()?[c]). (Available since C# 6)
a?[b]if a is not null then get bbinaryThis determines if an array or other structure is null before attempting to reference an item (numeric or identifier). Ternary use in conjunction with ?? to provide an alternative (e.g. a?[b]??c). Can be used in n-ary form with ?. for continual null-checks (e.g., a?.b()?[c]). (Available since C# 6)
@"a"verbatim "a"nullaryString constant of verbatim text, i.e., escape characters are ignored.
$"{b}"insert b into the string literaln-ary$ begins a string interpolation statement, which inserts substring(s) into the string literal, useful for quick string-building. A symbol name enclosed in {} will be evaluated to the string value, using ToString() where necessary. (Available since C# 6)
$@"{b}"insert b into the verbatim string literaln-aryCombines the functionality of @ and $. Brace literals can be designated by {{ and }} (Available since C# 6. NOTE: In C# 8 and beyond, the operators may be in either order.)
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.