C# Tutorial

C# examples, c# assignment operators, assignment operators.

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

Try it Yourself »

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

c# assignment operator expression

Member-only story

Expressions and Operators in C#

Dusan Velimirovic

Dusan Velimirovic

Dive into C# expressions and operators, understanding how to use constants, primary expressions, assignment expressions, and compound assignment operators. Learn to build and manipulate expressions effectively with practical examples.

Introduction

Expressions and operators are fundamental elements of programming in C#. An expression represents a value, and operators are used to perform operations on these values. In this article, we’ll explore the different types of expressions, including constants and primary expressions, and examine how operators, such as assignment and compound assignment operators, help you build and manage complex expressions.

Constant expression

Here is an example of a constant expression:

We can use the * operator to combine two operands (the literal expressions 12 and 30), as follows:

Primary Expressions

In C#, primary expressions are the fundamental expressions from which more complex expressions can be built . They serve as the basic building blocks in the language’s syntax and include identifiers, literals, and expressions formed with parentheses.

Dusan Velimirovic

Written by Dusan Velimirovic

Aspiring software engineer learning C#, .NET Core, Blazor and SQL. Sharing my journey and insights on Medium. Passionate about web development and coding.

Text to speech

Csharp Tutorial

  • C# Basic Tutorial
  • C# - Overview
  • C# - Environment
  • C# - Program Structure
  • C# - Basic Syntax
  • C# - Data Types
  • C# - Type Conversion
  • C# - Variables
  • C# - Constants
  • C# - Operators
  • C# - Decision Making
  • C# - Encapsulation
  • C# - Methods
  • C# - Nullables
  • C# - Arrays
  • C# - Strings
  • C# - Structure
  • C# - Classes
  • C# - Inheritance
  • C# - Polymorphism
  • C# - Operator Overloading
  • C# - Interfaces
  • C# - Namespaces
  • C# - Preprocessor Directives
  • C# - Regular Expressions
  • C# - Exception Handling
  • C# - File I/O
  • C# Advanced Tutorial
  • C# - Attributes
  • C# - Reflection
  • C# - Properties
  • C# - Indexers
  • C# - Delegates
  • C# - Events
  • C# - Collections
  • C# - Generics
  • C# - Anonymous Methods
  • C# - Unsafe Codes
  • C# - Multithreading
  • C# Useful Resources
  • C# - Questions and Answers
  • C# - Quick Guide
  • C# - Useful Resources
  • C# - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

C# - Assignment Operators

There are following assignment operators supported by C# −

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B assigns value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

The following example demonstrates all the assignment operators available in C# −

When the above code is compiled and executed, it produces the following result −

C# operator

last modified July 5, 2023

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

C# operator list

The following table shows a set of operators used in the C# language.

CategorySymbol
Sign operators
Arithmetic
Logical (boolean and bitwise)
String concatenation
Increment, decrement
Shift
Relational
Assignment
Member access
Indexing
Cast
Ternary
Delegate concatenation and removal
Object creation
Type information
Overflow exception control
Indirection and address
Lambda

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators . There is also one ternary operator ?: , which works with three operands.

Certain operators may be used in different contexts. For example the + operator. From the above table we can see that it is used in different cases. It adds numbers, concatenates strings or delegates; indicates the sign of a number. We say that the operator is overloaded .

C# unary operators

C# unary operators include: +, -, ++, --, cast operator (), and negation !.

C# sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to indicate that we have a positive number. It can be omitted and it is mostly done so.

The minus sign changes the sign of a value.

C# increment and decrement operators

The above two pairs of expressions do the same.

In the above example, we demonstrate the usage of both operators.

C# explicit cast operator

The explicit cast operator () can be used to cast a type to another type. Note that this operator works only on certain types.

In the example, we explicitly cast a float type to int .

Negation operator

In the example, we build a negative condition: it is executed if the inverse of the expression is valid.

C# assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

The previous expression does not make sense in mathematics. But it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x .

C# concatenating strings

The + operator is also used to concatenate strings.

C# arithmetic operators

SymbolName
Addition
Subtraction
Multiplication
/Division
Remainder

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

C# Boolean operators

SymbolName
logical and
logical or
negation

Boolean operators are also called logical.

Many expressions result in a boolean value. Boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

Example shows the logical and operator. It evaluates to true only if both operands are true.

Three of four expressions result in true.

The || , and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.

An example may clarify this a bit more.

In the second case, we use the || operator and use the Two method as the first operand. In this case, "Inside two" and "Pass" strings are printed to the terminal. It is again not necessary to evaluate the second operand, since once the first operand evaluates to true , the logical or is always true .

C# relational operators

Relational operators are used to compare values. These operators always result in boolean value.

SymbolMeaning
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal to

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In C# we use == to compare numbers. Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.

C# bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like C#.

SymbolMeaning
bitwise negation
bitwise exclusive or
bitwise and
bitwise or

The bitwise negation operator changes each 1 to 0 and 0 to 1.

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

C# compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.

The a variable is initiated to one. 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5; .

C# new operator

The new operator is used to create objects and invoke constructors.

C# access operator

The access operator [] is used with arrays, indexers, and attributes.

A dictionary is created. With domains["de"] , we get the value of the pair that has the "de" key.

C# index from end operator ^

The index from end operator ^ indicates the element position from the end of a sequence. For instance, ^1 points to the last element of a sequence and ^n points to the element with offset length - n .

In the example, we apply the operator on an array and a string.

We print the last letter of the word.

C# range operator ..

The .. operator specifies the start and end of a range of indices as its operands. The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range.

We create an array slice from index 1 till index 4; the last index 4 is not included.

C# type information

We use the sizeof and typeof operators.

The is operator checks if an object is compatible with a given type.

We create two objects from user defined types.

We have a Base and a Derived class. The Derived class inherits from the Base class.

The derived object is compatible with the Base class because it explicitly inherits from the Base class. On the other hand, the _base object has nothing to do with the Derived class.

The as operator is used to perform conversions between compatible reference types. When the conversion is not possible, the operator returns null. Unlike the cast operation which raises an exception.

We try to cast various types to the string type. But only once the casting is valid.

C# operator precedence

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

The following table shows common C# operators ordered by precedence (highest precedence first):

Operator(s)CategoryAssociativity
Primary Left
Unary Left
Multiplicative Left
Additive Left
Shift Left
Equality Right
Logical AND Left
Logical XOR Left
Logical OR Left
Conditional AND Left
Conditional OR Left
Null Coalescing Left
Ternary Right
Assignment Right

Operators on the same row of the table have the same precedence.

In this case, the negation operator has a higher precedence. First, the first true value is negated to false, then the | operator combines false and true, which gives true in the end.

C# associativity rule

Arithmetic, boolean, relational, and bitwise operators are all left to right associated.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.

C# null-conditional operator

A null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null. If the operand evaluates to null , the result of applying the operator is null.

We have a list of users. One of them is initialized with null values.

We use the ?. to access the Name member and call the ToUpper method. The ?. prevents the System.NullReferenceException by not calling the ToUpper on the null value.

In this example, we have a null value in an array. We prevent the System.NullReferenceException by applying the ?. operator on the array elements.

C# null-coalescing operator

The null-coalescing operator ?? is used to define a default value for a nullable type. It returns the left-hand operand if it is not null; otherwise it returns the right operand. When we work with databases, we often deal with absent values. These values come as nulls to the program. This operator is a convenient way to deal with such situations.

We want to assign a value to z variable. But it must not be null . This is our requirement. We can easily use the null-coalescing operator for that. In case both x and y variables are null, we assign -1 to z .

C# null-coalescing assignment operator

First, the list is assigned to null .

We use the ??= to assign a new list object to the variable. Since it is null , the list is assigned.

C# ternary operator

The ternary operator ?: is a conditional operator. It is a convenient operator for cases where we want to pick up one of two values, depending on the conditional expression.

In most countries the adulthood is based on your age. You are adult if you are older than a certain age. This is a situation for a ternary operator.

First the expression on the right side of the assignment operator is evaluated. The first phase of the ternary operator is the condition expression evaluation. So if the age is greater or equal to 18, the value following the ? character is returned. If not, the value following the : character is returned. The returned value is then assigned to the adult variable.

C# Lambda operator

Wherever we can use a delegate, we also can use a lambda expression. A definition for a lambda expression is: a lambda expression is an anonymous function that can contain expressions and statements. On the left side we have a group of data and on the right side an expression or a block of statements. These statements are applied on each item of the data.

In lambda expressions we do not have a return keyword. The last statement is automatically returned. And we do not need to specify types for our parameters. The compiler will guess the correct parameter type. This is called type inference.

The compiler will expect an int type. The val is a current input value from the list. It is compared if it is greater than 3 and a boolean true or false is returned. Finally, the FindAll will return all values that met the condition. They are assigned to the sublist collection.

The items of the sublist collection are printed to the terminal.

This is the same example. We use a anonymous delegate instead of a lambda expression.

C# calculating prime numbers

In the above example, we deal with many various operators. A prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. We pick up a number and divide it by numbers, from 1 up to the picked up number. Actually, we do not have to try all smaller numbers; we can divide by numbers up to the square root of the chosen number. The formula will work. We use the remainder division operator.

By definition, 1 is not a prime

We skip the calculations for 2 and 3: they are primes. Note the usage of the equality and conditional or operators. The == has a higher precedence than the || operator. So we do not need to use parentheses.

We are OK if we only try numbers smaller than the square root of a number in question. It was mathematically proven that it is sufficient to take into account values up to the square root of the number in question.

This is a while loop. The i is the calculated square root of the number. We use the decrement operator to decrease the i by one each loop cycle. When the i is smaller than 1, we terminate the loop. For example, we have number 9. The square root of 9 is 3. We divide the 9 number by 3 and 2.

C# operators and expressions

In this article we covered C# operators.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials .

Answertopia

C# 11 Operators and Expressions

This chapter covers using operators to create expressions when programming in C#, including arithmetic and assignment operators. Other topics covered include operator precedence, logical operators, and the ternary operator.

In the previous chapters, we used variables and constants in C# and described the different variable and constant types. However, being able to create constants and variables is only part of the story. The next step is using these variables and constants in C# code. The primary method for working with the data stored in constants and variables is in the form of expressions. This chapter will examine C# expressions and operators in detail.

What is an expression?

The most fundamental expression consists of an operator, two operands, and an assignment. The following is an example of an expression:

In the above example, the ( + ) operator adds two operands (1 and 2) together. The assignment operator ( = ) subsequently assigns the result of the addition to an integer variable named  theResult . The operands could have easily been variables or constants (or a mixture of each) instead of the actual numerical values used in the example.

In the remainder of this lesson, we will examine the various operators available in C#.

The basic assignment operator

We have already looked at the most basic of assignment operators, the  =  operator. This assignment operator assigns the result of an expression to a variable. In essence, the = assignment operator takes two operands. The left-hand operand is the variable to which a value is to be assigned, and the right-hand operand is the value to be assigned. The right-hand operand is, more often than not, an expression that performs some arithmetic or logical evaluation. The following examples are all valid uses of the assignment operator:

Assignment operators may also be chained to assign the same value to multiple variables. For example, the following code assigns the value 20 to the  x ,  y  and,  z  variables:

C# arithmetic operators

C# provides a range of operators to create mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-), which indicates that a value is negative rather than positive. This contrasts with the subtraction operator (-), which takes two operands (i.e., one value to be subtracted from another). For example:

The following table lists the primary C# arithmetic operators:

– (unary)Negates the value of a variable or expression
*Multiplication
/Division
+Addition
Subtraction
%Modulo

Note that multiple operators may be used in a single expression, for example:

While the above code is perfectly valid, it is essential to be aware that C# does not evaluate the expression from left to right or right to left but instead in an order specified by the precedence of the various operators that conform to basic mathematical principles. Operator precedence is an important topic to understand since it impacts the result of a calculation and will be covered in detail in the next section.

C# operator precedence

C# uses the same operator order concept as in basic mathematics. For example, we probably all learned from our school days that the answer to the following calculation is 210, not 300:

This is a direct result of  operator precedence . C# knows the same rules we learned at school that tell it which order operators should be evaluated in an expression. For example, C# correctly considers the multiplication operator ( * ) to be of higher precedence than the addition ( + ) operator.

Fortunately, the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses (another common concept in basic mathematics). For example:

In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300.

The following table outlines the C# operator precedence order from highest precedence to lowest:

Highest+, -, !, ~, ++x, –x, (T)x
* / %
+ –
<< >>
< > <= >= is as
== !=
&
^
|
&&
||
😕
Lowest=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=

It should come as no surprise that the assignment operators have the lowest precedence since you would not want to assign the result of an expression until that expression had been thoroughly evaluated. Don’t worry about memorizing the above table. Most programmers use parentheses to evaluate their expressions in the desired order.

Compound assignment operators

C# provides several operators to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows:

The above expression adds the value contained in variable x to the value contained in variable  y  and stores the result in variable  x . This can be simplified using the addition compound assignment operator ( += ):

The above expression performs the same task as  x = x + y  but saves the programmer some typing. This is yet another feature that C# has inherited from the C programming language. Numerous compound assignment operators are available in C#. The most frequently used are outlined in the following table:

OperatorDescription
x += yAdd x to y and place the result in x
x -= ySubtract y from x and place the result in x
x *= yMultiply x by y and place the result in x
x /= yDivide x by y and place the result in x
x %= yPerform Modulo on x and y and place the result in x
x &= yAssign to x the result of logical AND operation on x and y
x= y
x ^= yAssign to x the result of logical Exclusive OR on x and y

C# provides several operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows:

The above expression adds the value contained in variable  x  to the value contained in variable  y  and stores the result in variable  x . This can be simplified using the addition compound assignment operator ( += ):

Increment and decrement operators

Another helpful shortcut can be achieved using the C#  increment  and  decrement  operators. As with the compound assignment operators described in the previous section, consider the following C# code fragment:

These expressions increment and decrement the value of  x  by 1. Instead of using this approach, it is quicker to use the  ++  and  --  operators. The following examples perform the same tasks as the examples above:

These operators can be placed either before or after the variable name. If the operator is placed before the variable name, the increment or decrement is performed before any other operations are performed on the variable. For example, in the following example,  x  is incremented before it is assigned to  y , leaving  y  with a value of 10:

In the following example, the value of  x  (9) is assigned to variable  y  before the decrement is performed. Consequently, after the expression is evaluated, the value of y will be 9, and the value of  x  will be 8:

Comparison operators

In addition to mathematical and assignment operators, C# also includes a set of logical operators helpful in performing comparisons. These operators all return a Boolean ( bool )  true  or  false  result depending on the result of the comparison. These operators are binary in that they work with two operands.

Comparison operators are most frequently used in constructing program control flow. For example, an  if  statement may be built based on whether one value matches another:

The result of a comparison may also be stored in a  bool  variable. For example, the following code will result in a  true  value being stored in the variable named  result :

Clearly, 10 is less than 20, resulting in a true evaluation of the x < y expression. The following table lists the full set of C# comparison operators:

OperatorDescription
x == yReturns true if x is equal to y
x > yReturns true if x is greater than y
x >= yReturns true if x is greater than or equal to y
x < yReturns true if x is less than y
x <= yReturns true if x is less than or equal to y
x != yReturns true if x is not equal to y

Boolean logical operators

Another set of operators which return Boolean  true  and  false  values are the C# Boolean logical operators. These operators both return Boolean results and take Boolean values as operands. The key operators are NOT ( ! ), AND ( && ), OR ( || ), and XOR ( ^ ).

The NOT ( ! ) operator inverts the current value of a Boolean variable or the result of an expression. For example, if a variable named  flag  is currently  true , prefixing the variable with a  !  character will invert the value to  false :

The OR ( || ) operator returns  true  if one of its two operands evaluates to  true , otherwise, it returns  false . For example, the following example evaluates to  true  because at least one of the expressions on either side of the OR operator is  true :

The AND ( && ) operator returns  true  only if both operands evaluate to be  true . The following example will return  false  because only one of the two operand expressions evaluates to  true :

The XOR ( ^ ) operator returns  true  if one (and only one) of the two operands evaluates to  true . For example, the following example will return  true  since only one operator evaluates to be  true :

If both operands were evaluated to be  true  or both were  false  the expression would return  false .

Range and index operators

The C# range ( .. ) and ??? ( ^ ) operators allow you to declare ranges of values and are invaluable when working with collections such as arrays. Both of these operators will be covered in the chapter titled  Creating 2D, 3D, and Jagged Arrays in C# 11 .

The ternary operator

The C#  ternary operator  provides a shortcut way of making decisions. The syntax of the ternary operator is as follows:

The way this works is that  [condition]  is replaced with an expression that will return either  true  or  false . If the result is  true  then the expression that replaces the  [true expression]  is evaluated. Conversely, if the result was  false  , then the  [false expression]  is evaluated. Let’s see this in action:

The true and false expressions above simply output the largest value. In practice, this can be any valid expression. The following modification, for example, specifies a string value to be displayed for each outcome:

Null-coalescing operators

The  null-coalescing operator  ( ?? ) allows a default value to be used if an operand has a  null  value. The syntax for using this operator is as follows:

If the left operand is not  null , then the operand’s value is returned; otherwise, the expression returns the default operand value.

The following example will output text which reads “Welcome back, Customer” because the  customerName  variable is set to  null :

C# also includes the  null-coalescing assignment operator  ( ??= ), the syntax for which is as follows:

In this case, the value of operand2 will be assigned to operand1 only if operand1 is null. Otherwise, operand1 will remain unchanged.

In the following example, the value initially assigned to  customerName  remains unchanged since it does not contain a  null  value:

StevenSwiniarski's avatar

Operators are used to perform various operations on variables and values.

The following code snippet uses the assignment operator, = , to set myVariable to the value of num1 and num2 with an arithmetic operator operating on them. For example, if operator represented * , myVariable would be assigned a value of num1 * num2 .

Operators can be organized into the following groups:

  • Arithmetic operators for performing traditional math evaluations.
  • Assignment operators for assigning values to variables.
  • Comparison operators for comparing two values.
  • Logical operators for combining Boolean values.
  • Bitwise operators for manipulating the bits of a number.

Arithmetic Operators

C# has the following arithmetic operators:

  • Addition, + , returns the sum of two numbers.
  • Subtraction, - , returns the difference between two numbers.
  • Multiplication, * , returns the product of two numbers.
  • Division, / , returns the quotient of two numbers.
  • Modulus, % , returns the remainder of one number divided by another.

The ones above operate on two values. C# also has two unary operators:

  • Increment, ++ , which increments its single operand by one.
  • Decrement, -- , which decrements its single operand by one.

Unlike the other arithmetic operators, the increment and decrement operators change the value of their operand as well as return a value. They also return different results depending on if they precede or follow the operand. Preceding the operand returns the value of the operand before the operation. Following the operand returns the value of the operand after the operation.

Logical Operators

C# has the following logical operators:

  • The & (and) operator returns true if both operands are true .
  • The | (or) operator returns true if either operand is true .
  • The ^ (xor) operator returns true if only one of its operands are true
  • The ! (not) operator returns true if its single operand is false .
Note: & , | , and ^ are logical operators when the operands are bool types. When the operands are numbers they perform bitwise operations. See Bitwise Operators below.

The above operators always evaluate both operands. There are also these conditional “short circuiting” operators:

  • The && (conditional and) operator returns true if both operands are true . If the first operand is false , the second operand is not evaluated.
  • The || (conditional or) operator returns true if either operand is true . If the first operand is true the second operand is not evaluated.

Assignment Operators

C# includes the following assignment operators:

  • The = operator assigns the value on the right to the variable on the left.
  • The += operator updates a variable by incrementing its value and reassigning it.
  • The -= operator updates a variable by decrementing its value and reassigning it.
  • The *= operator updates a variable by multiplying its value and reassigning it.
  • The /= operator updates a variable by dividing its value and reassigning it.
  • The %= operator updates a variable by calculating its modulus against another value and reassigning it.

The assignment operators of the form op= , where op is a binary arithmetic operator, is a shorthand. The expression x = x op y; can be shortened to x op= y; . This compound assignment also works with the logical operators & , | and ^ .

  • The ??= operator assigns the value on the right to the variable on the left if the variable on the left is null .

Comparison Operators

C# has the following comparison operators:

  • Equal, == , for returning true if two values are equal.
  • Not equal, != , for returning true if two values are not equal.
  • Less than, < , for returning true if the left value is less than the right value.
  • Less than or equal to, <= , for returning true if the left value is less than or equal to the right value.
  • Greater than, > , for returning true if the left value is greater than the right value.
  • Greater than or equal to, >= , for returning true if the left value is greater than or equal to the right value.
Note: for these comparison operators, if any operand is not a number ( Double.NaN or Single.NaN ) the result of the operation is false .

Bitwise Operators

C# has the following operators that perform operations on the individual bits of a number.

  • Bitwise complement, ~ , inverts each bit in a number.
  • Left-shift, << , shifts its left operand left by the number of bits specified in its right operand. New right positions are zero-filled.
  • Right-shift, >> , shifts its left operand right by the number of bits specified in its right operand. For signed integers, left positions are filled with the value of the high-order bit. For unsigned integers, left positions are filled with zero.
  • Unsigned right-shift, >>> , same as >> except left positions are always zero-filled.
  • Logical AND, & , performs a bitwise logical AND of its operands.
  • Logical OR, | , performs a bitwise logical OR on its operands.
  • Logical XOR, ^ , performs a bitwise logical XOR on its operands.

All contributors

Looking to contribute.

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn C# on Codecademy

Computer science.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

arithmetic-operators.md

Latest commit, file metadata and controls.

title description ms.date author f1_keywords helpviewer_keywords

Arithmetic operators (C# reference)

The following operators perform arithmetic operations with operands of numeric types:

  • Unary ++ (increment) , -- (decrement) , + (plus) , and - (minus) operators
  • Binary * (multiplication) , / (division) , % (remainder) , + (addition) , and - (subtraction) operators

Those operators are supported by all integral and floating-point numeric types.

In the case of integral types, those operators (except the ++ and -- operators) are defined for the int , uint , long , and ulong types. When operands are of other integral types ( sbyte , byte , short , ushort , or char ), their values are converted to the int type, which is also the result type of an operation. When operands are of different integral or floating-point types, their values are converted to the closest containing type, if such a type exists. For more information, see the Numeric promotions section of the C# language specification . The ++ and -- operators are defined for all integral and floating-point numeric types and the char type. The result type of a compound assignment expression is the type of the left-hand operand.

Increment operator ++

The unary increment operator ++ increments its operand by 1. The operand must be a variable, a property access, or an indexer access.

The increment operator is supported in two forms: the postfix increment operator, x++ , and the prefix increment operator, ++x .

Postfix increment operator

The result of x++ is the value of x before the operation, as the following example shows:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="PostfixIncrement":::

Prefix increment operator

The result of ++x is the value of x after the operation, as the following example shows:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="PrefixIncrement":::

Decrement operator --

The unary decrement operator -- decrements its operand by 1. The operand must be a variable, a property access, or an indexer access.

The decrement operator is supported in two forms: the postfix decrement operator, x-- , and the prefix decrement operator, --x .

Postfix decrement operator

The result of x-- is the value of x before the operation, as the following example shows:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="PostfixDecrement":::

Prefix decrement operator

The result of --x is the value of x after the operation, as the following example shows:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="PrefixDecrement":::

Unary plus and minus operators

The unary + operator returns the value of its operand. The unary - operator computes the numeric negation of its operand.

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="UnaryPlusAndMinus":::

The ulong type doesn't support the unary - operator.

Multiplication operator *

The multiplication operator * computes the product of its operands:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="Multiplication":::

The unary * operator is the pointer indirection operator .

Division operator /

The division operator / divides its left-hand operand by its right-hand operand.

Integer division

For the operands of integer types, the result of the / operator is of an integer type and equals the quotient of the two operands rounded towards zero:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="IntegerDivision":::

To obtain the quotient of the two operands as a floating-point number, use the float , double , or decimal type:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="IntegerAsFloatingPointDivision":::

Floating-point division

For the float , double , and decimal types, the result of the / operator is the quotient of the two operands:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="FloatingPointDivision":::

If one of the operands is decimal , another operand can be neither float nor double , because neither float nor double is implicitly convertible to decimal . You must explicitly convert the float or double operand to the decimal type. For more information about conversions between numeric types, see Built-in numeric conversions .

Remainder operator %

The remainder operator % computes the remainder after dividing its left-hand operand by its right-hand operand.

Integer remainder

For the operands of integer types, the result of a % b is the value produced by a - (a / b) * b . The sign of the non-zero remainder is the same as the sign of the left-hand operand, as the following example shows:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="IntegerRemainder":::

Use the xref:System.Math.DivRem%2A?displayProperty=nameWithType method to compute both integer division and remainder results.

Floating-point remainder

For the float and double operands, the result of x % y for the finite x and y is the value z such that

  • The sign of z , if non-zero, is the same as the sign of x .
  • The absolute value of z is the value produced by |x| - n * |y| where n is the largest possible integer that is less than or equal to |x| / |y| and |x| and |y| are the absolute values of x and y , respectively.

This method of computing the remainder is analogous to that used for integer operands, but different from the IEEE 754 specification. If you need the remainder operation that complies with the IEEE 754 specification, use the xref:System.Math.IEEERemainder%2A?displayProperty=nameWithType method.

For information about the behavior of the % operator with non-finite operands, see the Remainder operator section of the C# language specification .

For the decimal operands, the remainder operator % is equivalent to the remainder operator of the xref:System.Decimal?displayProperty=nameWithType type.

The following example demonstrates the behavior of the remainder operator with floating-point operands:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="FloatingPointRemainder":::

Addition operator +

The addition operator + computes the sum of its operands:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="Addition":::

You can also use the + operator for string concatenation and delegate combination. For more information, see the + and += operators article.

Subtraction operator -

The subtraction operator - subtracts its right-hand operand from its left-hand operand:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="Subtraction":::

You can also use the - operator for delegate removal. For more information, see the - and -= operators article.

  • Compound assignment

For a binary operator op , a compound assignment expression of the form

is equivalent to

except that x is only evaluated once.

The following example demonstrates the usage of compound assignment with arithmetic operators:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="CompoundAssignment":::

Because of numeric promotions , the result of the op operation might be not implicitly convertible to the type T of x . In such a case, if op is a predefined operator and the result of the operation is explicitly convertible to the type T of x , a compound assignment expression of the form x op= y is equivalent to x = (T)(x op y) , except that x is only evaluated once. The following example demonstrates that behavior:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="CompoundAssignmentWithCast":::

In the preceding example, value 44 is the result of converting value 300 to the byte type.

In the checked overflow-checking context , the preceding example throws an xref:System.OverflowException. For more information, see the Integer arithmetic overflow section.

You also use the += and -= operators to subscribe to and unsubscribe from an event , respectively. For more information, see How to subscribe to and unsubscribe from events .

Operator precedence and associativity

The following list orders arithmetic operators starting from the highest precedence to the lowest:

  • Postfix increment x++ and decrement x-- operators
  • Prefix increment ++x and decrement --x and unary + and - operators
  • Multiplicative * , / , and % operators
  • Additive + and - operators

Binary arithmetic operators are left-associative. That is, operators with the same precedence level are evaluated from left to right.

Use parentheses, () , to change the order of evaluation imposed by operator precedence and associativity.

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="PrecedenceAndAssociativity":::

For the complete list of C# operators ordered by precedence level, see the Operator precedence section of the C# operators article.

Arithmetic overflow and division by zero

When the result of an arithmetic operation is outside the range of possible finite values of the involved numeric type, the behavior of an arithmetic operator depends on the type of its operands.

Integer arithmetic overflow

Integer division by zero always throws a xref:System.DivideByZeroException.

If integer arithmetic overflow occurs, the overflow-checking context, which can be checked or unchecked , controls the resulting behavior:

  • In a checked context, if overflow happens in a constant expression, a compile-time error occurs. Otherwise, when the operation is performed at run time, an xref:System.OverflowException is thrown.
  • In an unchecked context, the result is truncated by discarding any high-order bits that don't fit in the destination type.

Along with the checked and unchecked statements, you can use the checked and unchecked operators to control the overflow-checking context, in which an expression is evaluated:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="CheckedUnchecked":::

By default, arithmetic operations occur in an unchecked context.

Floating-point arithmetic overflow

Arithmetic operations with the float and double types never throw an exception. The result of arithmetic operations with those types can be one of special values that represent infinity and not-a-number:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="FloatingPointOverflow":::

For the operands of the decimal type, arithmetic overflow always throws an xref:System.OverflowException. Division by zero always throws a xref:System.DivideByZeroException.

Round-off errors

Because of general limitations of the floating-point representation of real numbers and floating-point arithmetic, round-off errors might occur in calculations with floating-point types. That is, the produced result of an expression might differ from the expected mathematical result. The following example demonstrates several such cases:

:::code language="csharp" interactive="try-dotnet-method" source="snippets/shared/ArithmeticOperators.cs" id="RoundOffErrors":::

For more information, see remarks at the System.Double , System.Single , or System.Decimal reference pages.

Operator overloadability

A user-defined type can overload the unary ( ++ , -- , + , and - ) and binary ( * , / , % , + , and - ) arithmetic operators. When a binary operator is overloaded, the corresponding compound assignment operator is also implicitly overloaded. A user-defined type can't explicitly overload a compound assignment operator.

User-defined checked operators

Beginning with C# 11, when you overload an arithmetic operator, you can use the checked keyword to define the checked version of that operator. The following example shows how to do that:

:::code language="csharp" source="snippets/shared/ArithmeticOperators.cs" id="CheckedOperator":::

When you define a checked operator, you must also define the corresponding operator without the checked modifier. The checked operator is called in a checked context ; the operator without the checked modifier is called in an unchecked context . If you only provide the operator without the checked modifier, it's called in both a checked and unchecked context.

When you define both versions of an operator, it's expected that their behavior differs only when the result of an operation is too large to represent in the result type as follows:

  • A checked operator throws an xref:System.OverflowException.
  • An operator without the checked modifier returns an instance representing a truncated result.

For information about the difference in behavior of the built-in arithmetic operators, see the Arithmetic overflow and division by zero section.

You can use the checked modifier only when you overload any of the following operators:

  • Unary ++ , -- , and - operators
  • Binary * , / , + , and - operators
  • Explicit conversion operators

The overflow-checking context within the body of a checked operator is not affected by the presence of the checked modifier. The default context is defined by the value of the CheckForOverflowUnderflow compiler option. Use the checked and unchecked statements to explicitly specify the overflow-checking context, as the example at the beginning of this section demonstrates.

C# language specification

For more information, see the following sections of the C# language specification :

  • Postfix increment and decrement operators
  • Prefix increment and decrement operators
  • Unary plus operator
  • Unary minus operator
  • Multiplication operator
  • Division operator
  • Remainder operator
  • Addition operator
  • Subtraction operator
  • The checked and unchecked operators
  • Numeric promotions
  • C# operators and expressions
  • xref:System.Math?displayProperty=nameWithType
  • xref:System.MathF?displayProperty=nameWithType
  • Numerics in .NET

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Addition operators - + and +=

  • 11 contributors

The + and += operators are supported by the built-in integral and floating-point numeric types, the string type, and delegate types.

For information about the arithmetic + operator, see the Unary plus and minus operators and Addition operator + sections of the Arithmetic operators article.

String concatenation

When one or both operands are of type string , the + operator concatenates the string representations of its operands (the string representation of null is an empty string):

String interpolation provides a more convenient way to format strings:

Beginning with C# 10, you can use string interpolation to initialize a constant string when all the expressions used for placeholders are also constant strings.

Beginning with C# 11, the + operator performs string concatenation for UTF-8 literal strings. This operator concatenates two ReadOnlySpan<byte> objects.

Delegate combination

For operands of the same delegate type, the + operator returns a new delegate instance that, when invoked, invokes the left-hand operand and then invokes the right-hand operand. If any of the operands is null , the + operator returns the value of another operand (which also might be null ). The following example shows how delegates can be combined with the + operator:

To perform delegate removal, use the - operator .

For more information about delegate types, see Delegates .

Addition assignment operator +=

An expression using the += operator, such as

is equivalent to

except that x is only evaluated once.

The following example demonstrates the usage of the += operator:

You also use the += operator to specify an event handler method when you subscribe to an event . For more information, see How to: subscribe to and unsubscribe from events .

Operator overloadability

A user-defined type can overload the + operator. When a binary + operator is overloaded, the += operator is also implicitly overloaded. A user-defined type can't explicitly overload the += operator.

C# language specification

For more information, see the Unary plus operator and Addition operator sections of the C# language specification .

  • C# operators and expressions
  • How to concatenate multiple strings
  • Arithmetic operators
  • - and -= operators

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assignment in lambda expression

I want to define some lambda expression that represent updates of properties of instances of a class.

I try to write that as below:

But I have a compilation error:

Error CS0832 An expression tree may not contain an assignment operator.

How to represent this update with a lambda.

My goal is for a business service to send updates to a generic repository. This repository could analyze the expression of the lambdas to build query to send to the database engine.

An example of a business service could be:

Eric Lippert's user avatar

  • 1 Why do you want to do this, as obviously you cant? however, if we can work out the why we might be able to give you something else –  TheGeneral Commented Mar 7, 2019 at 0:08
  • 1 Assuming you are asking about Expression because you want to transform it yourself you can use == workaround similar to Moq approach - Mock.Of<User>( m => m.Name == "wahtever" && m.Email == " [email protected] "); ... but it is not clear from the question what your actual goal is - so not an answer (also based on comment to Eric's answer it is likely what you want) –  Alexei Levenkov Commented Mar 7, 2019 at 0:49
  • 1 I changed the title; the operator that assigns a value to a variable or property is the assignment operator. An assignation is a secret meeting between lovers having an affair. :-) –  Eric Lippert Commented Mar 9, 2019 at 17:20
  • Your update makes it more clear what's going on here. LINQ was not designed to represent "update" queries that mutate the database. It was only designed to represent queries that extract data: selection, grouping, joining, filtering, sorting, and so on. –  Eric Lippert Commented Mar 13, 2019 at 16:09

3 Answers 3

You can't always get what you want.

We designed expression-tree lambdas to represent non-mutating operations, so using = , += , ++ and so on in an expression-tree lambda is illegal.

How to represent this update with a lambda?

Delegate lambdas have no such restriction; you can say

Can you say more about why you need this? There might be a better way to achieve your goal. You may be asking an XY question . That is a question where you have a problem, you have a bad solution, and now you are asking a question about the bad solution instead of about the problem. What's the problem you're trying to solve?

  • 1 I have a business service that wants to sends updates of an entity to a generic repository. So I wanted that service pass updates as lambda expressions to the repository. An example of repository call from a service could be like : repository.Update(x => x.Id == userid, x => x.FirstName = "John", x => x.LastName = "Foo") . The first parameter is the filter of entities to update, the next are updates to apply. The repository could translate into query to the database engine by analyzing expressions. –  gentiane Commented Mar 7, 2019 at 0:32
  • There is an Expression.Assign(Expression, Expression) Method . So this seems to be a C# restriction and not an Expression restriction. –  Olivier Jacot-Descombes Commented Mar 7, 2019 at 1:53
  • 3 @OlivierJacot-Descombes: That's correct. We created expression trees for LINQ, but needed to add more nodes to it for the DLR, but never added support for the new nodes to the C# compiler. –  Eric Lippert Commented Mar 7, 2019 at 6:27
  • 1 "You can't always get what you want." But if you try sometimes, you might find you get what you need. –  D Stanley Commented Mar 13, 2019 at 16:04

As others have said, C# does not allow assignment expressions in expression trees.

An alternative approach would be to use a new expression. This would allow to express the update with a single lambda:

where x represents the old state of the entity in the update expression.

If you don't need to reference the old value, you can use this simplified signature (according to your comment):

Olivier Jacot-Descombes's user avatar

  • 1 I tried workaround used by Moq replacing assignment = by a equlity == . But it causes many problems (enum are casted..). So I switched to your suggestion, but with a simplified version that does not use the old state. It works fine. The method signature is void Update(Expression<Func<T, bool>> filter, Expression<Func<T>> update) –  gentiane Commented Mar 9, 2019 at 23:11

It is hard to guess how you want to use your Expression. If you want to dive deep into reflections, maybe this snippet will help:

In there you:

1) Define the ParameterExpression - your input;

2) Set up how to get to the property of the class that you are interested ( .Name )

3) Finally, define the expression (and compile-call it) to do stuff wqith a test user variable

JleruOHeP's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c# or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Generating function for A261041
  • Multiplicity of the smallest non-zero Laplacian eigenvalue for tree graphs
  • Why does each leg of my 240V outlet measure 125V to ground, but 217V across the hot wires?
  • Advanced Composite Solar Sail (ACS3) Orbit
  • Where is this railroad track as seen in Rocky II during the training montage?
  • is it possible to add a stepwise counter for assigning a number to each text block?
  • Question about word (relationship between language and thought)
  • How can I add a neutral to a 240V to 120V circuit conversion?
  • Potential Syscall Note Loophole?
  • On the convex cone of convex functions
  • subtle racism in the lab
  • What is the missing fifth of the missing fifths?
  • Can the planet Neptune be seen from Earth with binoculars?
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • Which volcano is more hazardous? Mount Rainier or Mount Hood?
  • Safari causes high CPU load for no reason, launchservicesd active
  • What is the resulting initiative order when a readied action triggers after a summoned monsters action but before the summoner?
  • Do US universities invite faculty applicants from outside the US for an interview?
  • Unable to understand a proof of the squeeze theorem
  • Is reading sheet music difficult?
  • What is the least number of colours Peter could use to color the 3x3 square?
  • Would it be out of style to start a history book with a poem I wrote?
  • Is the 2024 Ukrainian invasion of the Kursk region the first time since WW2 Russia was invaded?
  • Why a minus sign is often put into the law of induction for an inductor

c# assignment operator expression

COMMENTS

  1. Assignment operators

    Assignment operators (C# reference)

  2. c#

    This would be very simple if I were able to assign via a Lambda expression (below) //An expression tree cannot contain an assignment operator. Expression<Func<ComplexObj, object>> expression = obj => obj.Contacts[0].FirstName = "Tim"; This code above is invalid due to the assignment operator. I need to pass a lambda expression in order to ...

  3. Operators and expressions

    List all operators and expression - C# reference

  4. C# Assignment Operators

    C# Assignment Operators

  5. Expressions

    Expressions - C# language specification

  6. Understanding C# Expressions and Operators: A Comprehensive Guide

    An assignment expression uses the = operator to assign the result of another expres‐ sion to a variable; for example: ... This article provides an in-depth look at C# expressions and operators ...

  7. C#

    C# - Assignment Operators

  8. docs/docs/csharp/language-reference/operators/assignment ...

    Assignment operators (C# reference) The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the ...

  9. C# operator

    C# compound assignment operators. The compound assignment operators consist of two operators. They are shorthand operators. a = a + 3; a += 3; The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable. Other compound operators are:

  10. C# 11 Operators and Expressions

    The most fundamental expression consists of an operator, two operands, and an assignment. The following is an example of an expression: int theResult = 1 + 2; Code language: C# (cs) In the above example, the ( +) operator adds two operands (1 and 2) together. The assignment operator ( =) subsequently assigns the result of the addition to an ...

  11. C#

    The /= operator updates a variable by dividing its value and reassigning it. The %= operator updates a variable by calculating its modulus against another value and reassigning it. The assignment operators of the form op=, where op is a binary arithmetic operator, is a shorthand. The expression x = x op y; can be shortened to x op= y;.

  12. docs/docs/csharp/language-reference/operators/index.md at main

    The simplest C# expressions are literals (for example, integer and real numbers) and names of variables. You can combine them into complex expressions by using operators. ... The assignment operators, the null-coalescing operators, lambdas, and the conditional operator ?: are right-associative. For example, x = y = z is evaluated as x = (y = z).

  13. Arithmetic operators (C# reference)

    Learn about C# operators that perform multiplication, division, remainder, addition, and subtraction operations with numeric types. 07/25/2022. pkulikov ++_CSharpKeyword ... The result type of a compound assignment expression is the type of the left-hand operand. Increment operator ++ The unary increment operator ++ increments its operand by 1.

  14. ?? and ??= operators

    and ??= operators - null-coalescing operators - C# reference

  15. ?: operator

    the ternary conditional operator - C# reference

  16. c#

    Because the right side of the assignment contains a complex expression, the lambda expression on the right cannot be resolved to a type. In order to make the expression compile, you have to give the compiler actual type information: Expression<Func<Foo, bool>> filterExpression = id.HasValue ?(Expression<Func<Foo, bool>>) (w => w.Id == id.Value) : null;

  17. Lambda expressions

    Lambda expressions and anonymous functions - C#

  18. Addition operators

    Addition operators - + and += - C# reference

  19. c#

    2. As others have said, C# does not allow assignment expressions in expression trees. An alternative approach would be to use a new expression. This would allow to express the update with a single lambda: x => x.Id == userId, // Where clause. x => new User{ // Update expression.