Categories
Technology Writing

Creating C# Applications: Chapter 3

When I work with more than one programming language at a time, such as Java and Perl or VB and C#, the biggest problem I have keeping the languages untangled is remembering to use a semi-colon (;) or not when ending the statement. No matter how hard I try to keep my language syntax separate, I always include the semi-colon when I shouldn’t (such as in VB), or not include it when I should (such as in C++ or Java or C#).

Regardless of the sophistication of a programming language, you must first become proficient with the operators and special characters supported in the language before advancing on its more escoteric elements, and this chapter provides coverage of C#’s operators and special character set — including the infamous semi-colon.

Arithmetic and Concatenation Characters

The simplest of the operators for C# are the arithmetic operators. The addition operator (‘+’) is used to add two numbers together, as it’s used in most other programming languages, such as C++. In addition, the + operator is an example of an overloaded operator within C#. What this means is that you can use it for adding numbers and you can also use it to add two strings together (concatenation), or add a string and a number. An overloaded operator is one that can work with different parameters, or parameter types. C# extends this capability by also translating parameters to compatible types — such as converting an integer to a string for concatenation when adding a string and an integer.

To demonstrate this capability, in the following code, the addition operator is used to add two numbers and two strings and print out the results of both operations.

using System;

class ArithTest 
{
   public static void Main() 
   {
        int i = 6;
	     string s1 = "Value";
        string s2 = " is ";

        // add two numbers
        i = i + 4;
        
        // add two strings
        s1 = s1 + s2;

        // add a string and a number
	     s2 = s1 + i;

        // output values
        Console.WriteLine(i);
        Console.WriteLine(s1);
        Console.WriteLine(s2);
      
   }
}

The result from running this application is:

10
Value is
Value is 10

The plus sign can’t convert automatically between the two operands if the result is ambiguous, or disallowed for implicit type conversion. If you try to add a double to an integer, as shown in the following line of code:

i = i + 4.15

An error results when you compile the application because you can’t implicitly convert a double to an integer.

The addition operator can also be used to perform delegate concatenation, covered in more detail in Chapter 10 “Delegates and Events”.

The addition operator is both a binary operator, meaning that there are two operands for an expression containing the operator, and a unary operator. A unary operator applies to only one operand. Applying the addition operator as a unary operator to an operand just returns the value of the operand:

nVal = i+;

The subtraction operator (‘-‘) is used to subtract one number from another, or to negate the value of an operand, as demonstrated in the following code:

using System;

class ArithTest 
{
   public static void Main() 
   {
        int i = 6;

        // subtract smaller value
        Console.WriteLine(i - 2);

        // subtract larger value
        Console.WriteLine(i - 7);

        // unary
        Console.WriteLine(-i);
      
   }
}

The following values are output when this application is run:

4
-1
-6

The subtraction operator, as with the other arithmetic operators, works with all numeric data types, such as integers, doubles, and decimals.

The multiplication operator (‘*’) multiplies two operands together, while the division operator (‘/’) divides the first number by the second. The modulus operator (‘%’) returns only the remainder after the first operand is divided by the second.

In the following code, each of the operators just described is used between two different operands, both of which are type double, and the results are printed out:

 
using System;

class ArithTest 
{
   public static void Main() 
   {
        double d1 = 4.15;
        double d2 = 1.23;

        //  multiply
        Console.WriteLine(d1 * d2);

        // divide
        Console.WriteLine(d1 / d2);

        // modulus
        Console.WriteLine(d1 % d2);
      
   }
}

The output of this application is:

5.1045
3.3739837398374
0.46 

The multiplication operator is another example of an overloaded operator; it’s also used when declaring pointers, and de-referencing these pointers to access the pointer values as you’ll see in the section “Membership, Array, and Casting Operators” later in this chapter.

With all arithmetic operations, if an overflow occurs because the result is too large for the allowed range of the data type, an OverflowException is thrown if one of the following conditions is met:

  • The checked compiler option is used and
  • The data types of the operands are integers (int, long, or ulong)
  • Or the operands are decimals

Use the checked compiler option when compiling the application in order to generate an OverflowException with integers. This compiler option turns on arithmetic checking:

csc /checked test.cs

In the following C# application, the OverflowException is captured and the error message printed out:

 
using System;

class ArithTest 
{
   public static void Main() 
   {
        int i = 2147148000;
        int i2 = 32000;

        try 
        {
           //  multiply
           i = i * i2;
           Console.WriteLine(i);
        }
        catch (OverflowException e)
        {
           Console.WriteLine("{0}", e);
        }
      
   }
}

When the application is compiled without the checked option, the following output results:

2144165888

Since integer arithmetic checking isn’t turned on, the significant high-order bits are discarded, and the resulting value is returned. When checking is turned on with the check compiler option, the following exception message is printed out:

System.OverflowException: An exception of type 
   System.OverflowException was thrown.
   at ArithTest.Main() 

The OverflowException will occur with all decimal values when the value is too large for the decimal format.

Float and double values don’t generate an overflow exception. Following the IEEE 754 arithmetic specification, values too large for the variable are set to infinity. If a value can’t be defined as a numeric, it is given the constant NaN — meaning Not a Number.

Arithmetic and concatenation operators are useful for converting values, but have no impact on an application’s process. In addition, each of the variables modified by the operators in this section first had to be assigned. Program flow controlled through the use of logical and condition operators and the assignment operators are discussed next.

Print Friendly, PDF & Email