Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

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

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

C# operators and expressions

  • 2023-03-09
Feedback

In this article

C# provides a number of operators. Many of them are supported by thebuilt-in types and allow you to perform basic operations with values of those types. Those operators include the following groups:

Typically, you canoverload those operators, that is, specify the operator behavior for the operands of a user-defined type.

The simplest C# expressions are literals (for example,integer andreal numbers) and names of variables. You can combine them into complex expressions by using operators. Operatorprecedence andassociativity determine the order in which the operations in an expression are performed. You can use parentheses to change the order of evaluation imposed by operator precedence and associativity.

In the following code, examples of expressions are at the right-hand side of assignments:

int a, b, c;a = 7;b = a;c = b++;b = a + b * c;c = a >= 100 ? b : c / 10;a = (int)Math.Sqrt(b * b + c * c);string s = "String literal";char l = s[s.Length - 1];List<int> numbers = [..collection];b = numbers.FindLast(n => n > 1);

Typically, an expression produces a result and can be included in another expression. Avoid method call is an example of an expression that doesn't produce a result. It can be used only as astatement, as the following example shows:

Console.WriteLine("Hello, world!");

Here are some other kinds of expressions that C# provides:

  • Interpolated string expressions that provide convenient syntax to create formatted strings:

    var r = 2.3;var message = $"The area of a circle with radius {r} is {Math.PI * r * r:F3}.";Console.WriteLine(message);// Output:// The area of a circle with radius 2.3 is 16.619.
  • Lambda expressions that allow you to create anonymous functions:

    int[] numbers = { 2, 3, 4, 5 };var maximumSquare = numbers.Max(x => x * x);Console.WriteLine(maximumSquare);// Output:// 25
  • Query expressions that allow you to use query capabilities directly in C#:

    int[] scores = { 90, 97, 78, 68, 85 };IEnumerable<int> highScoresQuery =    from score in scores    where score > 80    orderby score descending    select score;Console.WriteLine(string.Join(" ", highScoresQuery));// Output:// 97 90 85

You can use anexpression body definition to provide a concise definition for a method, constructor, property, indexer, or finalizer.

Operator precedence

In an expression with multiple operators, the operators with higher precedence are evaluated before the operators with lower precedence. In the following example, the multiplication is performed first because it has higher precedence than addition:

var a = 2 + 2 * 2;Console.WriteLine(a); //  output: 6

Use parentheses to change the order of evaluation imposed by operator precedence:

var a = (2 + 2) * 2;Console.WriteLine(a); //  output: 8

The following table lists the C# operators starting with the highest precedence to the lowest. The operators within each row have the same precedence.

OperatorsCategory or name
x.y,f(x),a[i],x?.y,x?[y],x++,x--,x!,new,typeof,checked,unchecked,default,nameof,delegate,sizeof,stackalloc,x->yPrimary
+x,-x,!x,~x,++x,--x,^x,(T)x,await,&x,*x,true and falseUnary
x..yRange
switch,withswitch andwith expressions
x * y,x / y,x % yMultiplicative
x + y,x – yAdditive
x << y,x >> y,x >>> yShift
x < y,x > y,x <= y,x >= y,is,asRelational and type-testing
x == y,x != yEquality
x & yBoolean logical AND orbitwise logical AND
x ^ yBoolean logical XOR orbitwise logical XOR
x | yBoolean logical OR orbitwise logical OR
x && yConditional AND
x || yConditional OR
x ?? yNull-coalescing operator
c ? t : fConditional operator
x = y,x += y,x -= y,x *= y,x /= y,x %= y,x &= y,x |= y,x ^= y,x <<= y,x >>= y,x >>>= y,x ??= y,=>Assignment and lambda declaration

For information about the precedence oflogical pattern combinators, see thePrecedence and order of checking of logical patterns section of thePatterns article.

Operator associativity

When operators have the same precedence, associativity of the operators determines the order in which the operations are performed:

  • Left-associative operators are evaluated in order from left to right. Except for theassignment operators and thenull-coalescing operators, all binary operators are left-associative. For example,a + b - c is evaluated as(a + b) - c.
  • Right-associative operators are evaluated in order from right to left. The assignment operators, the null-coalescing operators, lambdas, and theconditional operator?: are right-associative. For example,x = y = z is evaluated asx = (y = z).

Important

In an expression of the formP?.A0?.A1, ifP isnull, neitherA0 norA1 are evaluated. Similarly, in an expression of the formP?.A0.A1, becauseA0 isn't evaluated whenP is null, neither isA0.A1. See theC# language specification for more details.

Use parentheses to change the order of evaluation imposed by operator associativity:

int a = 13 / 5 / 2;int b = 13 / (5 / 2);Console.WriteLine($"a = {a}, b = {b}");  // output: a = 1, b = 6

Operand evaluation

Unrelated to operator precedence and associativity, operands in an expression are evaluated from left to right. The following examples demonstrate the order in which operators and operands are evaluated:

ExpressionOrder of evaluation
a + ba, b, +
a + b * ca, b, c, *, +
a / b + c * da, b, /, c, d, *, +
a / (b + c) * da, b, c, +, /, d, *

Typically, all operator operands are evaluated. However, some operators evaluate operands conditionally. That is, the value of the leftmost operand of such an operator defines if (or which) other operands should be evaluated. These operators are the conditional logicalAND (&&) andOR (||) operators, thenull-coalescing operators?? and??=, thenull-conditional operators?. and?[], and theconditional operator?:. For more information, see the description of each operator.

C# language specification

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

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo