Tuesday, April 18, 2017

Lesson 5: C# Operators


C# Operators

In c#, operators are symbols that are used to perform certain operations; the operations that an operator performs depends on the type and number of operands. Operands are values in which an operator perform certain operation on it and they can be variables, integer literals, string literals or any return value from a method. For example:
Based on the number of operands, operators in C# can be classified in to three categories – unary operator, binary operator and ternary operator.
1.    Unary operator is an operator that takes only one operand to produce some value.
2.    Binary operator is an operator that takes two operands to operate.
3.    Ternary operator, represented by ?:, is an operator that takes three operands and it is used to perform some conditional operation.

A unary operator takes the following form:

            Operator operand or operand operator

For example: -45, numberOfStudents++; both – and ++ are unary operators that act on -45 and numberOfStudents respectively.

A binary operator takes the following form:

Left hand operand operator Right hand operand

For example: int netSalary = basicSalary – totalDeductions;

A ternary operator takes the following general form:

operand1 operator1 operand2 operator2 operand3

For example: boolean isTaxed = (netIncome > 5000) ? true: false;
Apart from the way operators in C# are classified on the basis of the number operands they have, they are also classified according the type of operations they perform.

The following subsequent topics briefly discusses common C# operators:

Arithmetic Operators

These operators are used to perform such math operations as addition, subtraction, multiplication, division and so on; the following table lists arithmetic operators that are commonly used in C#.










Vital Notes:
  1. When addition, subtraction, multiplication or division is performed, the operand are promoted to the higher sized datatype. For example: adding a double and int will result a double value.
  2. When byte and short values are added, you might get an unexpected result and therefore it is worthwhile to cast the result to the desired type as is shown in the following code snippet.
byte b1;
b1 = 20;
byte b2 = 30;
byte b3 = 40;
b1 = b2 + b3; // A compile-time error. Cannot explicitly convert type ‘int’ to ‘byte’

The correct usage without any compilation error is as follows:
b1 = (byte)(b2 + b3);

Relational Operators

In C#, relational operators take two operands, and the result produced by a relational operator is always a boolean value: true or false.

The following table presents the list of relational operators that C# offers at your disposal.         













Boolean Logical Operators

The output of any boolean logical operator is true or false. Boolean logical operators are used only with boolean operands; the following table lists the boolean logical operators which are commonly used in C#.
















Ternary Operator (?:)

C# has a very concise operator called ternary operator; it is also called conditional operator, and it is named as ternary operators for it takes three operands. The general form of a ternary operator is shown below.


The operation of ternary operators is quite interesting as it deserves some explanation.

u  Both "?" and ":" make the ternary operator.
u  If the boolean-expression evaluates to true, it evaluates the true-expression; otherwise, it evaluates false-expression.
u  For example:
int age = 20;
              string isCharged = (age>18) ? "Yes" : "No";
    In the above piece of code, the variable isCharged is assigned Yes for the output of the relational expression age>18 is true. Had the value of age was a  value less than 18 the value of isCharged would have been No.

    The following program demonstrates how above discussed operators are used in C#.




    /*
     * Author: Temesghen Tekeste
     * Basic operation of C# Operators
     * */
    using System;

    namespace OperatorsDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Declering some variables for various operations
                double a = 100.0, b = 21;
                double addition, subtraction, multiplication, division, modulo;

                //1.    Arithmetic Operators      
                //performing the desired operation
                addition = a + b;
                subtraction = a - b;
                multiplication = a * b;
                division = a / b;
                modulo = a % b; // modulo = 16 b/se 100 % 21 = 21 * 4 + 16

                //Outputing the resutl of above arithmetic operations
                Console.WriteLine("Arithmetic Operators:");
                Console.WriteLine("\tAddition: {0} + {1} = {2}", a, b, addition);
                Console.WriteLine("\tSubtraction: {0} - {1} = {2}", a, b, subtraction);
                Console.WriteLine("\tMultiplication: {0} * {1} = {2}", a, b, multiplication);
                Console.WriteLine("\tDivision: {0} / {1} = {2}", a, b, division);
                Console.WriteLine("\tModulo Remainder: {0} % {1} = {2}", a, b, modulo);

                //2.    Relational Operators
                //performing the desired operation
                bool isEqualTo = a == b;
                bool isGreater = a >= b;
                bool isLessThanOrEqual = a <= b;
                bool isNotEqualTo = a != b;


                //Outputing the resutl of above relational operations
                Console.WriteLine("Relational Operators:");
                Console.WriteLine("\t==: {0} == {1} = {2}", a, b, isEqualTo);
                Console.WriteLine("\t>: {0} > {1} = {2}", a, b, isGreater);
                Console.WriteLine("\t<=: {0} <= {1} = {2}", a, b, isLessThanOrEqual);
                Console.WriteLine("\t!=: {0} != {1} = {2}", a, b, isNotEqualTo);

                //3.    Logical Operators
                //performing the desired operation
                bool logicalAnd = (a>b)&&(a == b);
                bool logicalOr = (a==101)||(a >= b);
                bool logicalNot = !(a <= b);
               
                //Outputing the resutl of above relational operations
                Console.WriteLine("Logical Operators:");
                Console.WriteLine("\t&&: ({0} > {1})&&({0} == {1}) = {2}", a, b, logicalAnd);
                Console.WriteLine("\t||: ({0} == {1})||({0} > {1}) = {2}", a, b, logicalOr);
                Console.WriteLine("\t!:  !({0} <= {1}) = {2}", a, b, logicalNot);
              

                //4.     Ternary  Operators
                int age = 20;
                String isCharged = (age>18) ? "Yes" : "No";
                //Outputing the resutl of above ternary operation
                Console.WriteLine("Ternary Operator:");
                Console.WriteLine("\tIs {0} years old charged? {1}.", age, isCharged);
                Console.ReadKey();
            }
        }
    }

    No comments:

    Post a Comment