Algorithm
In C#, operator precedence determines the order in which operators are evaluated in an expression, and associativity defines the order in which operators of the same precedence are evaluated. Here is a summary of the operator precedence and associativity in C#:
Operator Precedence (from highest to lowest):
- Postfix operators:
x++
,x--
- Unary operators:
+x
,-x
,!x
,~x
,++x
,--x
,(T)x
,await
,sizeof
,typeof
,checked
,unchecked
- Multiplicative operators:
*
,/
,%
- Additive operators:
+
,-
- Shift operators:
<<
,>>
- Relational and type testing operators:
<
,>
,<=
,>=
,is
,as
- Equality operators:
==
,!=
- Logical AND operator:
&&
- Logical OR operator:
||
- Null-coalescing operator:
??
- Conditional operator:
? :
- Assignment operators:
=
,+=
,-=
,*=
,/=
,%=
etc. - Lambda operator:
=>
Associativity:
- Most binary operators are left-associative, meaning they are evaluated from left to right. For example,
x + y + z
is equivalent to(x + y) + z
. - The assignment operators (
=
,+=
,-=
etc.) are right-associative, meaning they are evaluated from right to left. For example,x = y = z
is equivalent tox = (y = z)
.
It's important to be aware of operator precedence and associativity to avoid unexpected behavior in your code. You can use parentheses to explicitly specify the order of evaluation when needed.
Code Examples
#1 Operator Precedence in C# Programming
Code -
C# Programming
using System;
namespace Operator
{
class OperatorPrecedence
{
public static void Main(string[] args)
{
int result1;
int a = 5, b = 6, c = 4;
result1 = --a * b - ++c;
Console.WriteLine(result1);
bool result2;
result2 = b >= c + a;
Console.WriteLine(result2);
}
}
}
Copy The Code &
Try With Live Editor
Output
False
#2 Associativity of Operators in C# Programming
Code -
C# Programming
using System;
namespace Operator
{
class OperatorPrecedence
{
public static void Main(string[] args)
{
int a = 5, b = 6, c = 3;
int result = a * b / c;
Console.WriteLine(result);
a = b = c;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
}
}
}
Copy The Code &
Try With Live Editor
Output
a = 3, b = 3, c = 3
Demonstration
C# Program Operator Precedence and Associativity