C#
  Home arrow C# arrow Page 2 - Behind the Scenes Look at C#: Operators
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Behind the Scenes Look at C#: Operators
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 32
    2005-06-29

    Table of Contents:
  • Behind the Scenes Look at C#: Operators
  • Arithmetic Operators
  • The Unary Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Assignment Operators
  • The Ternary Operator
  • Operator Precedence

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Behind the Scenes Look at C#: Operators - Arithmetic Operators


    (Page 2 of 8 )

    Like all programming languages, C# supports the basic arithmetic operators: the addition operator (+), multiplication operator (*), subtraction operator (-) and the division operator(/), plus the module operator (%). C# also supports the increment and decrement operators (++ and --). Let's take a look at examples for using these operators. Copy the following code and compile it:

    using System;
    namespace Operators
    {
    class Class1
    {
    static void Main(string[] args)
    {
    int x = 10;
    int y = 5;
    int result;

    result = x + y;
    Console.WriteLine("x + y = {0}", result);

    result = x - y;
    Console.WriteLine("x - y = {0}", result);

    result = x * y;
    Console.WriteLine("x * y = {0}", result);

    result = x / y;
    Console.WriteLine("x / y = {0}", result);

    Console.ReadLine();
    }
    }
    }

    You will get the following result in the console window:

    The add operator (+) takes two arguments and returns their sum. Note that when you use two different primitive types for the arguments, the C# compiler tries to convert one of the arguments' data types to ensure the integrity of the operation. For example, take a look at the following expression:

    double x = 9 + 8.5;

    The result is 17.5, as you expected -- but what happened is that the C# compiler implicitly converted (we will discuss type conversion after we finish C# operators) the 9 to 9.00 so that the expression could evaluate and produce the value. The same rules apply for the other basic arithmetic operators (*, - and /).

    You can write the Main method as follows, too:

    static void Main(string[] args)
    {
    int x = 10;
    int y = 5;
    int result;

    Console.WriteLine("x + y = {0}", x + y);

    Console.WriteLine("x - y = {0}", x - y);

    Console.WriteLine("x * y = {0}", x * y);

    Console.WriteLine("x / y = {0}", x / y);

    Console.ReadLine();
    }

    And it will produce the same value, here we just passed the expression as the method argument so it will be evaluated and printed to the console window. Otherwise, the value would be stored in the result variable and then used it as an argument.

    Modify the Main method as follows:

    static void Main(string[] args)
    {
    int x = 10;
    int y = 4;

    Console.WriteLine("x / y = {0}", x / y);

    Console.ReadLine();
    }

    You may expect that the result of the expression x / y is 2.5, and in fact it is, but the C# compiler will assume that the return type of the expression int / int is int, too, and the result will be 2 (not 2.5). The C# compiler will make an implicit conversion on the result. The solution of this problem is to declare the variables as double:

    static void Main(string[] args)
    {
    double x = 10;
    double y = 4;
    double result = x / y;
    Console.WriteLine("x / y = {0}", result);

    Console.ReadLine();
    }

    The result then will be 2.5, as expected.

    We can use the module operator (%) to get the remainder of the division of two numbers. For instance, with the same example as above, if we replaced the division operator with the module operator we would have the value 2:

    static void Main(string[] args)
    {
    double x = 10;
    double y = 4;
    double result = x % y;
    Console.WriteLine("x % y = {0}", result);

    Console.ReadLine();
    }

    10 / 4 is equal to 2.5. We said that the module operator returns the remainder of the division operation, which in our case is 0.5, which gives us 2. You may recall from reading the article "Branching and Looping in C#, Part 1" when we used the module operator to test if the input number is an even or an odd number:

    int x = Convert.ToInt32(Console.ReadLine());
    if(x % 2 == 0)
    {
    Console.WriteLine("this is an EVEN number");
    }
    else
    {
    Console.WriteLine("this is an ODD number");
    }

    If x Module 2 is equal to 0, this means that it's an even number; if it's not 0 (we have a remainder in this case) then it's an odd number. This is a common use of the module operator, and in many scenarios you will find it a reliable method to construct your algorithms.

    The increment and the decrement unary operators (++ and --) need a little discussion because they have two versions, the postfix and prefix versions. Before we explain how these operators work, copy the following code and compile it:

    using System;
    namespace Operators
    {
    class Class1
    {
    static void Main(string[] args)
    {
    int x = 5;

    Console.WriteLine("x = {0}", x);
    Console.WriteLine("++x value = {0}", ++x);
    Console.WriteLine("x = {0}", x);
    x = 5;
    Console.WriteLine("x++ value = {0}", x++);
    Console.WriteLine("x = {0}", x);
    Console.ReadLine();
    }
    }
    }

    If this is the first time you have encountered these operators, you will be surprised at the result:

    We have 5 assigned to x, then we execute the expression ++x, which increases the value of x by 1. We use this new value in the current expression, and we again print the value of x, which is 6. Again we reassign 5 to x and execute the expression x++, which does nothing at all in the current statement -- that's why x maintains the value of 5 in the current expression. It does its job in the next expression, however, where it increases the value of x by 1.

    Put simply, the pre-increment operator (++x) increases the value of x by 1 in the current expression, and also uses this new value in the current expression. The post-increment operator (x++) will not increase the value of x in the current expression (it will use the current value of x) but it will increase x by 1 in the next statement. The pre-decrement operator (--x) decrements the value of x by 1 in the current expression, and use this new value in the current expression. The post-decrement operator (x--) maintains the value of x in the current expression and then increases it by 1 in the next statement.

    Let's look at the MSIL code of the above application:

    .method private hidebysig static void Main(string[] args) cil managed
    {
    .entrypoint
    // Code size 99 (0x63)
    .maxstack 4
    .locals init (int32 V_0)
    IL_0000: ldc.i4.5
    IL_0001: stloc.0
    IL_0002: ldstr "x = {0}"
    IL_0007: ldloc.0
    IL_0008: box [mscorlib]System.Int32
    IL_000d: call void [mscorlib]System.Console::WriteLine(string, object)
    IL_0012: ldstr "++x value = {0}"
    IL_0017: ldloc.0
    IL_0018: ldc.i4.1
    IL_0019: add
    IL_001a: dup
    IL_001b: stloc.0
    IL_001c: box [mscorlib]System.Int32
    IL_0021: call void [mscorlib]System.Console::WriteLine(string, object)
    IL_0026: ldstr "x = {0}"
    IL_002b: ldloc.0
    IL_002c: box [mscorlib]System.Int32
    IL_0031: call void [mscorlib]System.Console::WriteLine(string, object)
    IL_0036: ldc.i4.5
    IL_0037: stloc.0
    IL_0038: ldstr "x++ value = {0}"
    IL_003d: ldloc.0
    IL_003e: dup
    IL_003f: ldc.i4.1
    IL_0040: add
    IL_0041: stloc.0
    IL_0042: box [mscorlib]System.Int32
    IL_0047: call void [mscorlib]System.Console::WriteLine(string, object)
    IL_004c: ldstr "x = {0}"
    IL_0051: ldloc.0
    IL_0052: box [mscorlib]System.Int32
    IL_0057: call void [mscorlib]System.Console::WriteLine(string, object)
    IL_005c: call string [mscorlib]System.Console::ReadLine()
    IL_0061: pop
    IL_0062: ret
    } // end of method Class1::Main

    There's much to explain here, but it would take an article of its own, so I will be brief and discuss only the difference between the pre-increment and post-increment operators. What we note from the above MSIL code is when the new value of x is produced. For the pre-increment operator, the add opcode is called before the value of x is placed on the stack, which increases the value by 1, and the new value 6 is ready for us to use in the current expression. For the post-increment operator, the add opcode is called after the value has been placed on the stack, which is 5, then it will be increased by 1 and ready to use for the next expression.

    More C# Articles
    More By Michael Youssef


     

    C# ARTICLES

    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#
    - Working with Regular Expressions in C#
    - Sending Simple E-Mail in C#
    - Building C# Comparable Objects: IComparable ...
    - Color Transformation Applications in C# GDI+...
    - Performing Color Transformation Operations i...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT