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):

  1. Postfix operators: x++, x--
  2. Unary operators: +x, -x, !x, ~x, ++x, --x, (T)x, await, sizeof, typeof, checked, unchecked
  3. Multiplicative operators: *, /, %
  4. Additive operators: +, -
  5. Shift operators: <<, >>
  6. Relational and type testing operators: <, >, <=, >=, is, as
  7. Equality operators: ==, !=
  8. Logical AND operator: &&
  9. Logical OR operator: ||
  10. Null-coalescing operator: ??
  11. Conditional operator: ? :
  12. Assignment operators: =, +=, -=, *=, /=, %= etc.
  13. 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 to x = (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

x
+
cmd
19
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

x
+
cmd
10
a = 3, b = 3, c = 3
Advertisements

Demonstration


C# Program Operator Precedence and Associativity