By 22/07/2015 14 Comments

C# Operator Precedence

  • In c# all operators have their own precedence means some will be executed first and some will be executed at the end.
  • In c# all operators does not have equal precedence, some operators have higher precedence than others, means those operators which has higher precedence are executed first by c# compiler, and those which has lowest precedence are executed at the end.

Example:

using System;
namespace csharpBasic
{
    // Start class definition / declaration.
    class Program
    {
        // Static main method void type declaration.
        static void Main(string[] args)
        {
            // Initialize an int type with value 5.
            int givenValue = 5;

            // Declare an int type result variable.
            int result;

            /* An expression which is assigned to result variable.
               In this expression 5 * 2 will be 
               executed first and answer will be 10, 
               after than, 10 will be added with givenValue which is 5 means 10 + 5 
               and the correct answer will be 15
               because Multiplication has high precedence than addition.
            */
            result = givenValue + 5 * 2; 

            // Print result.
            Console.WriteLine("5 + 5 * 2 = {0} ", result);
            Console.ReadKey();

        } // End of main method definition. 
    } // End of class. 
}

Table describes the order of operator’s precedence in C#. In this table the operator which is defined at top has highest priority means these operators executed first in an expression and the operators which is defined in bottom has lowest priority:

GROUP OPERATOR(S)
Primary ( ), ., [ ], x++, x- -, new, typeof, sizeof, checked, unchecked
Unary +, -, !, ~, ++x, –x, and casts
Multiplication and Division *, /, %
Addition and Subtraction +, –
Bitwise Shift Operators <<, >>
Relational <, >, <=, >=, is, as
Comparison ==, !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Boolean AND &&
Boolean OR ||
Ternary Operator ?:
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=





Next Tutorial →


← Previous Tutorial


Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .