C# Programming/Operators
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
[edit | edit source]The following arithmetic operators operate on numeric operands (arguments a
and b
in the "expression" below).
Expression | Read | Arity | 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 | edit source]The following logical operators operate on boolean or integral operands, as noted.
Expression | Read | Arity | 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 | edit source]Expression | Read | Arity | 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 | edit source]The binary relational operators ==
, !=
, <
, >
, <=
, and >=
are used for relational operations and for type comparisons.
Expression | Read | Arity | Explanation |
---|---|---|---|
a == b |
a is equal to b |
binary | 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 |
binary | 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 |
binary | The operator < operates on integral types. It returns true, if a is less than b , false otherwise.
|
a > b |
a is greater than b |
binary | 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 |
binary | 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 |
binary | The operator >= operates on integral types. It returns true, if a is greater than or equal to b , false otherwise.
|
Assignment
[edit | edit source]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).
Expression | Read | Arity | Explanation |
---|---|---|---|
a = b |
a equals (or set to) b |
binary | 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 |
n-ary | 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 . 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
[edit | edit source]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.
Expression | Read | Arity | Explanation |
---|---|---|---|
a += b |
a plus equals (or increment by) b |
binary | Equivalent to a = a + b .
|
a -= b |
a minus equals (or decrement by) b |
binary | Equivalent to a = a - b .
|
a *= b |
a multiply equals (or multiplied by) b |
binary | Equivalent to a = a*b .
|
a /= b |
a divide equals (or divided by) b |
binary | Equivalent to a = a/b .
|
a %= b |
a mod equals b |
binary | Equivalent to a = a%b .
|
a &= b |
a and equals b |
binary | Equivalent to a = a&b .
|
a |= b |
a or equals b |
binary | Equivalent to a = a|b .
|
a ^= b |
a xor equals b |
binary | Equivalent to a = a^b .
|
a <<= b |
a left-shift equals b |
binary | Equivalent to a = a << b .
|
a >>= b |
a right-shift equals b |
binary | Equivalent to a = a >> b .
|
Type information
[edit | edit source]Expression | Read | Arity | Explanation |
---|---|---|---|
x is T |
is x of type T |
binary | 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 |
cast x to T |
binary | 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) |
size of x |
unary | returns 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 T |
unary | 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 | edit source]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 | Read | Arity | Explanation |
---|---|---|---|
*a |
object at a |
unary | Indirection operator. Allows access the object being pointed. |
a->member |
member member of a |
binary | Similar to the . operator. Allows access to members of classes and structs being pointed.
|
a[b] |
object at offset b from a |
binary | Used to index a pointer. |
&a |
reference to a |
unary | References the address of the pointer. |
stackalloc a |
allocate a on the stack |
binary | Allocates memory on the stack, rather than the heap. See C Sharp Programming/Keywords/stackalloc. |
fixed a |
prevent a from being relocated |
binary | Temporarily fixes a variable in order that its address may be found. See C Sharp Programming/Keywords/fixed. |
Overflow exception control
[edit | edit source]Expression | Read | Arity | Explanation |
---|---|---|---|
checked(a) |
evaluate a and check for overflow |
unary | uses overflow checking on value a . See C Sharp Programming/Keywords/checked.
|
unchecked(a) |
evaluate a without checking for overflow |
unary | avoids overflow checking on value a . See C Sharp Programming/Keywords/unchecked.
|
Others
[edit | edit source]Expression | Read | Arity | Explanation |
---|---|---|---|
a.b |
member b of a |
binary | Accesses 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 a |
binary | Returns the value of index b in a . Arrays use 0-origin indexing.
|
(a)b |
cast b to type a |
binary | Explicitly 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 a |
create a new a |
n-ary | Creates 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 + b |
concatenate string b to the end of string a |
binary | 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 |
concatenate delegate b to delegate a |
binary | If a and b are delegates, performs delegate concatenation.
|
a ? b : c |
if a then b else c |
ternary | If 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 ?? b |
if a is null then b else a |
binary | If 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?.b |
if a is not null then evaluate b |
binary | This 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 b |
binary | This 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" |
nullary | String constant of verbatim text, i.e., escape characters are ignored. |
$"{b}" |
insert b into the string literal |
n-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 literal |
n-ary | Combines 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.)
|