Core C#

Other Operators

This C# program demonstrates how various operators are used.

Program.cs

using System;

namespace XoaX {
    class Program {

        static void Main(string[] args) {
            int iMyInt = 1303515112;
            Console.WriteLine("The unary + and - operators");
            Console.WriteLine("+iMyInt = " + (+iMyInt));
            Console.WriteLine("-iMyInt = " + (-iMyInt));
            Console.WriteLine();

            int[] iaArray = new int[] { 38, 187, 271};
            Console.WriteLine("The index [] operator");
            Console.WriteLine("iaArray[0] = " + iaArray[0]);
            Console.WriteLine("iaArray[1] = " + iaArray[1]);
            Console.WriteLine("iaArray[2] = " + iaArray[2]);
            Console.WriteLine();

            int iLargeIntValue = 2147483647;
            int iSum = 0;
            Console.WriteLine("Checked overflow");
            try {
                iSum = checked(iLargeIntValue + 10);
            } catch (System.OverflowException e) {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("iSum = " + iSum);
            Console.WriteLine();

            Console.WriteLine("Unchecked overflow");
            try {
                iSum = unchecked(iLargeIntValue + 10);
            } catch (System.OverflowException e) {
                // No exception is thrown. So, it is not caught.
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("iSum = " + iSum);
        }
    }
}
 

Output

The unary + and - operators
+iMyInt = 1303515112
-iMyInt = -1303515112

The index [] operator
iaArray[0] = 38
iaArray[1] = 187
iaArray[2] = 271

Checked overflow
Arithmetic operation resulted in an overflow.
iSum = 0

Unchecked overflow
iSum = -2147483639
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.