C Sharp/Operator Precedence

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators

C# - Flow Control
C# - Variables II
C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

[edit] C# assignment Operator


This section will discuss C# operator precedence. It is very crucial in evaluating mathmatical expressions



  • Refer to the chart below for the operator precedence ranking.


C# Operator Precedence

Precedence Operators
High ++, -- (Prefixes)
%, /, *
+, -
=, *=, /=, %=, +=, -=
Low ++, -- (Suffixes)


Lets take a look at some example C# code:


int result = 12 + 3 * 2 - 1;


Just like basic algebra, we always evaluate multiplication first because it is higher on the precedence chart.


  • First: 3 * 2 = 6 Expression: 12 + 6 - 1
  • Second: 12 + 6 - 1 = 17


Now the result is 12 + 3 * 2 - 1 = 17


[edit] Parenhesis in Expression

You can force precedence in an expression by using the paraenthesis. Lets take the same expression a above and insert parenthsis in it.


int result = (12 + 3) * 2 - 1;

We must evaluate the parenthesis first to solve this expression.

  • First: (12 + 3) = 15 Expression: 15 * 2 - 1
  • Second: Evaluate (15 * 2) = 30 Expression: 30 -1
  • Third: 30 - 1 = 29


Result: 29


Lets look at some real code:


using System;
 
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(12 + 3 * 2 - 1);
        Console.WriteLine((12 + 3) * 2 - 1);
        Console.Read();
    }
}

Output:

17

29