Fundamental C# Operators

Introduction

An operation is an action performed on one or more values either to modify the value held by one or both of the variables, or to produce a new value by combining existing values. Therefore, an operation is performed using at least one symbol and at least one value. The symbol used in an operation is called an operator. A value involved in an operation is called an operand.

A unary operator is an operator that performs its operation on only one operand. An operator is referred to as binary if it operates on two operands. An operator is terciary if it is used on three operands.

Practical LearningPractical Learning: Introducing Operators and Operands

  1. Start Microsoft Visual Studio (if Microsoft Visual Studio is already opened, to create a new application, on the main menu, click File -> New -> Project...
  2. In the Create a New Project, in the list of projects templates, click Empty Project (.NET Framework)
  3. Click Next
  4. Change the Name to GeorgetownDryCleaningServices2 and click OK
  5. To create a file for the code, on the main menu, click Project -> Add New Item...
  6. In the left list of the Add New Item dialog box, click Code
  7. In the middle list, click Code File
  8. Change the Name to OrderProcessing
  9. Click Add

Curly Brackets { }

Curly brackets are probably the most used and the most tolerant operators of C#. Fundamentally, curly brackets are used to create a section of code. As such they are required to delimit the bodies of namespaces, classes, structures, exceptions, etc. They are also optionally used in conditional statements. Curly brackets are also used to create variable scope. Here is an example:

class Order
{
}

Parentheses ( )

Parentheses are used to isolate a group of items that must be considered as belonging to one entity. For example, parentheses are used to differentiate a method such as Main from a regular variable. Here is an example:

class Exercise
{
    static void Main()
    {
    }
}

Parentheses can also be used to isolate an operation or an expression with regard to another operation or expression.

Semi-Colon;

The semi-colon is used to indicate the end of an expression or a declaration. Here is an example:

int number;

As we will learn, there are other uses of the semi-colon.

The Comma ,

The comma is used to separate variables used in a group. For example, a comma can be used to delimit the names of variables that are declared with the same data type. Here is an example:

class Exercise
{
    static void Main()
    {
    	string firstName, lastName, fullName;
    }
} 

The comma can also be used to separate the member of an enumeration or the arguments of a method. We will review all of them when the time comes.

The Assignment =

When you declare a variable, a memory space is reserved for it. That memory space may be empty until you fill it with a value. To "put" a value in the memory space allocated to a variable, you can use the assignment operator represented as =. Based on this, the assignment operation gives a value to a variable. Its syntax is:

VariableName = Value

The VariableName factor must be a valid variable name. It cannot be a value such as a numeric value or a (double-quoted) string. Here is an example that assigns a numeric value to a variable:

class Exercise
{
    static void Main()
    {
		double salary;

		// Using the assignment operator
		salary = 12.55;
    }
}

Once a variable has been declared and assigned a value, you can call Write() or WriteLine() to display its value.  Here is an example:

class Exercise
{
    static void Main()
    {
		double salary;

		// Using the assignment operator
		salary = 12.55;
		System.Console.Write("Employee's Hourly Salary: ");
		System.Console.WriteLine(salary);
    }
}

This would produce:

Employee's Hourly Salary: $12.55

The above code declares a variable before assigning it a value. You will usually perform this assignment when you want to change the value held by a variable. Providing a starting value to a variable when the variable is declared is referred to as initializing the variable. Here is an example:

class Exercise
{
    static void Main()
    {
		// Using the assignment operator
		double salary = 12.55;

		System.Console.Write("Employee's Hourly Salary: ");
		System.Console.WriteLine(salary);
    }
}

We saw that you can declare various variables at once by using the same data type but separating their names with commas. When doing this, you can also initialize each variable by assigning it the desired value before the comma or the semi-colon. Here is an example:

class Exercise
{
    static void Main()
    {
		// Initializing various variables when declaring them with the same data type
		double value1 = 224.58, value2 = 1548.26;
			
		System.Console.Write("Value 1 = ");
		System.Console.WriteLine(value1);
		System.Console.Write("Value 2 = ");
		System.Console.WriteLine(value2);
		System.Console.WriteLine();
    }
}

This would produce:

Value 1 = 224.58
Value 2 = 1548.26

Double-Quotes "

The double-quote " is used to delimit a string. Like the single-quote, the double-quote is usually combined with another. Between the combination of double-quotes, you can include an empty space, a character, a word, or a group of words, making it a string. Here is an example:

class Exercise
{
    static void Main()
    {
		System.Console.WriteLine("The Wonderful World of C#!!!");
    }
}

A double-quoted string can also be declared and then assigned to a variable.

Practical LearningPractical Learning: Introducing Operators

  1. In the empty document, type the following code:
    class Exercise
    {
        static void Main()
        {
            string customerName      = "Harriet Roberts",
                   homePhone         = "(240) 927-9372";
            int    numberOfShirts    = 1,
                   numberOfPants     = 1,
                   numberOfDresses   = 1;
            double priceOneShirt     = 1.35,
                   priceAPairOfPants = 2.25,
                   priceOneDress     = 3.50;
            int    orderMonth        = 6,
                   orderDay          = 22,
                   orderYear         = 2020;
            double mondayDiscount = 0.25; // 25%;
    
            System.Console.WriteLine("-/-Georgetown Cleaning Services -/-");
            System.Console.WriteLine("===================================");
    
            System.Console.Write("Customer:   ");
            System.Console.WriteLine(customerName);
            System.Console.Write("Home Phone: ");
            System.Console.WriteLine(homePhone);
            System.Console.Write("Order Date: ");
            System.Console.Write(orderMonth);
            System.Console.Write('/');
            System.Console.Write(orderDay);
            System.Console.Write('/');
            System.Console.WriteLine(orderYear);
            System.Console.WriteLine("-----------------------------------");
            System.Console.WriteLine("Item Type  Qty Sub-Total");
            System.Console.WriteLine("------------------------");
            System.Console.Write("Shirts      ");
            System.Console.Write(numberOfShirts);
            System.Console.Write("     ");
            System.Console.WriteLine(priceOneShirt);
            System.Console.Write("Pants       ");
            System.Console.Write(numberOfPants);
            System.Console.Write("     ");
            System.Console.WriteLine(priceAPairOfPants);
            System.Console.Write("Dresses     ");
            System.Console.Write(numberOfDresses);
            System.Console.Write("     ");
            System.Console.WriteLine(priceOneDress);
            System.Console.WriteLine("-----------------------------------");
            System.Console.Write("Monday Discount: ");
            System.Console.Write(mondayDiscount);
            System.Console.WriteLine('%');
            System.Console.WriteLine("===================================");
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging. This would produce:
    -/-Georgetown Cleaning Services -/-
    ===================================
    Customer:   Harriet Roberts
    Home Phone: (240) 927-9372
    Order Date: 6/22/2020
    -----------------------------------
    Item Type  Qty Sub-Total
    ------------------------
    Shirts      1     1.35
    Pants       1     2.25
    Dresses     1     3.5
    -----------------------------------
    Monday Discount: 0.25%
    ===================================
    Press any key to continue . . .
  3. Press Enter and return to your programming environment

Introduction to Arithmetic Operators

The Positive Operator +

Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive:

-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞
   0
-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side.

As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value doesn't display a sign, it is referred as unsigned.

To express a variable as positive or unsigned, you can just type it. here is an example:

class Exercise
{
    static void Main()
    {
		// Displaying an unsigned number
		System.Console.Write("Number = ");
		System.Console.WriteLine(+802);
    }
}

This would produce:

Number = 802

The Negative Operator -

As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. xamples are -12, -448, -32706. A value accompanied by - is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

Here is an example that uses two variables. One has a positive value while the other has a negative value:

class Exercise
{
    static void Main()
    {
		// Displaying an unsigned number
		System.Console.Write("First Number  ");
		System.Console.WriteLine(+802);
		// Displaying a negative number
		System.Console.Write("Second Number ");
		System.Console.WriteLine(-802);
    }
}

This would produce:

First Number  802
Second Number -802

Introduction to the Addition Operations

The addition is an operation used to add things of the same nature one to another, as many as necessary. Sometimes, the items are added one group to another. The concept is still the same, except that this last example is faster. The addition is performed in mathematics using the + sign. The same sign is used in C#. Here is an example that adds two numbers:

class Exercise
{
    static void Main()
    {
		System.Console.Write("244 + 835 = ");
		System.Console.WriteLine(244 + 835);
    }
}

Here is the result:

244 + 835 = 1079

You can also add some values already declared and initialized in your program. You can also get the values from the user.

Practical LearningPractical Learning: Using the Addition Operator

  1. To use the addition, change the file as follows:
    class Exercise
    {
        static void Main()
        {
            string customerName      = "James Burreck",
                   homePhone         = "(202) 301-7030";
            int    numberOfShirts    = 1,
                   numberOfPants     = 1,
                   numberOfDresses   = 1;
            int totalNumberOfItems;
            double priceOneShirt     = 0.95,
                   priceAPairOfPants = 2.95,
                   priceOneDress     = 4.55;
            int orderMonth = 3, orderDay = 15, orderYear = 2019;
    
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("========================");
            System.Console.Write("Customer:   ");
            System.Console.WriteLine(customerName);
            System.Console.Write("Home Phone: ");
            System.Console.WriteLine(homePhone);
            System.Console.Write("Order Date: ");
            System.Console.Write(orderMonth);
            System.Console.Write("/");
            System.Console.Write(orderDay);
            System.Console.Write("/");
            System.Console.WriteLine(orderYear);
            System.Console.WriteLine("------------------------");
            System.Console.WriteLine("Item Type  Qty Sub-Total");
            System.Console.WriteLine("------------------------");
            System.Console.Write("Shirts      ");
            System.Console.Write(numberOfShirts);
            System.Console.Write("     ");
            System.Console.WriteLine(priceOneShirt);
            System.Console.Write("Pants       ");
            System.Console.Write(numberOfPants);
            System.Console.Write("     ");
            System.Console.WriteLine(priceAPairOfPants);
            System.Console.Write("Dresses     ");
            System.Console.Write(numberOfDresses);
            System.Console.Write("     ");
            System.Console.WriteLine(priceOneDress);
            System.Console.WriteLine("------------------------");
            System.Console.Write("Number of Items: ");
            System.Console.WriteLine(totalNumberOfItems);
            System.Console.WriteLine("========================");
        }
    }
  2. Execute the program. This would produce:
    -/- Georgetown Cleaning Services -/-
    ========================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2019
    ------------------------
    Item Type  Qty Sub-Total
    ------------------------
    Shirts      1     0.95
    Pants       1     2.95
    Dresses     1     4.55
    ------------------------
    Number of Items: 3
    ========================
  3. Close the DOS window and return to your programming environment

Introduction String Addition

You can apply the addition operation on strings the same way you would on numeric calues. You can use the + operator on strings as in "Pie" + "Chart". This would produce "PieChart". You can also apply the operator to string variables. Here is an example:

class Exercise
{
    static void Main()
    {
        string firstName = "Alexander";
        string lastName  = "Kallack";
        string fullName  = firstName + " " + lastName;

        System.Console.Write("Full Name: ");
        System.Console.WriteLine(fullName);
    }
}

This would produce:

Full Name: Alexander Kallack
Press any key to continue . . .

String Addition and Other Types

You can add the value of any type to a string. The result is a new string. Here is an example:

class EmployeesRecords
{   
    static void Main()
    {
        double rate = 17.82;
        string salary = "Hourly Salary: ";

        string result = salary + rate;

        System.Console.WriteLine(result);
}

Embedding an Operation

We already know that, to display a value, you can put it in the parentheses of System.Console.Write() or System.Console.WriteLine(). Instead of a value, you can include an operation in those parentheses. Here is an example that adds two strings in the parentheses of System.Console.WriteLine():

class EmployeesRecords
{   
    static void Main()
    {
        System.Console.WriteLine("Red Oak " + "High School");
    }
}

Of course, you can also include an operation that involves more than two operands. Here is an example:

class EmployeesRecords
{   
    static void Main()
    {
        string mainTitle = "Red Oak High School";
        string subTitle  = "Students Records";

        System.Console.Write(mainTitle + " - " + subTitle);
    }
}

In the same way, in the parentheses, you can add any value to a string. Here is an example:

class EmployeesRecords
{   
    static void Main()
    {
        string salary = "Hourly Salary: ";
        double rate = 17.82;

        System.Console.WriteLine(salary + rate);
    }
}

Introduction to the Multiplication Operation

The multiplication allows adding one value to itself a certain number of times, set by a second value. As an example, instead of adding a value to itself in this manner: A + A + A + A, since the variable a is repeated over and over again, you could simply find out how many times A is added to itself, then multiply a by that number which, is this case, is 4. This would mean adding a to itself 4 times, and you would get the same result.

Just like the addition, the multiplication is associative: a * b * c = c * b * a. When it comes to programming syntax, the rules we learned with the addition operation also apply to the multiplication.

Here is an example:

class Exercise
{
    static void Main()
    {
        // Initializing various variables when declaring them with the same data type
        double value1 = 224.58, value2 = 1548.26;
        double result = value1 * value2;

        System.Console.Write(value1);
        System.Console.Write(" * ");
        System.Console.Write(value2);
        System.Console.Write(" = ");
        System.Console.WriteLine(result);
        System.Console.WriteLine();
    }
}

This would produce:

224.58 * 1548.26 = 347708.2308

Press any key to continue . . .

Practical LearningPractical Learning: Using the Multiplication Operator

  1. To multiply, change the document as follows:
    class Exercise
    {
        static void Main()
        {
            double priceOneShirt = 0.95;
            double priceAPairOfPants = 2.95;
            double priceOneDress = 4.55;
            string customerName = "James Burreck",
                   homePhone = "(202) 301-7030";
            int    numberOfShirts = 5,
                   numberOfPants = 2,
                   numberOfDresses = 3;
            int    totalNumberOfItems;
            double subTotalShirts, subTotalPants, subTotalDresses;
            double totalOrder;
            int    orderMonth = 3, orderDay = 15, orderYear = 2002;
    
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
            subTotalShirts = priceOneShirt * numberOfShirts;
            subTotalPants = priceAPairOfPants * numberOfPants;
            subTotalDresses = numberOfDresses * priceOneDress;
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("====================================");
            System.Console.Write("Customer:   ");
            System.Console.WriteLine(customerName);
            System.Console.Write("Home Phone: ");
            System.Console.WriteLine(homePhone);
            System.Console.Write("Order Date: ");
            System.Console.Write(orderMonth);
            System.Console.Write("/");
            System.Console.Write(orderDay);
            System.Console.Write("/");
            System.Console.WriteLine(orderYear);
            System.Console.WriteLine("------------------------------------");
            System.Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Shirts      ");
            System.Console.Write(numberOfShirts);
            System.Console.Write("     ");
            System.Console.Write(priceOneShirt);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalShirts);
            System.Console.Write("Pants       ");
            System.Console.Write(numberOfPants);
            System.Console.Write("     ");
            System.Console.Write(priceAPairOfPants);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalPants);
            System.Console.Write("Dresses     ");
            System.Console.Write(numberOfDresses);
            System.Console.Write("     ");
            System.Console.Write(priceOneDress);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalDresses);
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Number of Items: ");
            System.Console.WriteLine(totalNumberOfItems);
            System.Console.Write("Total Order:     ");
            System.Console.WriteLine(totalOrder);
            System.Console.WriteLine("====================================");
        }
    }
  2. Execute the application to see the result. This would produce:
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Number of Items: 10
    Total Order:     24.30
    ====================================
  3. Close the DOS window and return to your programming environment

Introduction to the Subtraction Operation

The subtraction operation is used to take out or subtract a value from another value. It is essentially the opposite of the addition. The subtraction is performed with the - sign. Here is an example:

class Exercise
{
    static void Main()
    {
		// Values used in this program
		double value1 = 224.58, value2 = 1548.26;
		double result = value1 - value2;

		System.Console.Write(value1);
		System.Console.Write(" - ");
		System.Console.Write(value2);
		System.Console.Write(" = ");
		System.Console.WriteLine(result);
    }
}

This would produce:

224.58 - 1548.26 = -1323.68

Press any key to continue . . .

Unlike the addition, the subtraction is not associative. In other words, a - b - c is not the same as c - b - a. Consider the following program that illustrates this:

class Exercise
{
    static void Main()
    {
		// This tests whether the addition is associative
		System.Console.WriteLine(" =+= Addition =+=");
		System.Console.Write("128 + 42 +   5 = ");
		System.Console.WriteLine(128 + 42 + 5);
		System.Console.Write("  5 + 42 + 128 = ");
		System.Console.WriteLine(5 + 42 + 128);
	
		System.Console.WriteLine();

		// This tests whether the subtraction is associative
		System.Console.WriteLine(" =-= Subtraction =-=");
		System.Console.Write("128 - 42 -   5 = ");
		System.Console.WriteLine(128 - 42 - 5);
		System.Console.Write("  5 - 42 - 128 = ");
		System.Console.WriteLine(5 - 42 - 128);
			
		System.Console.WriteLine();
    }
}

This would produce:

=+= Addition =+=
128 + 42 +   5 = 175
  5 + 42 + 128 = 175

 =-= Subtraction =-=
128 - 42 -   5 = 81
  5 - 42 - 128 = -165

Notice that both operations of the addition convey the same result. In the subtraction section, the numbers follow the same order but produce different results.

Practical LearningPractical Learning: Using the Subtraction Operator

  1. To subtract, change the document as follows:
    class Order
    {
        static void Main()
        {
            double priceOneShirt = 0.95;
            double priceAPairOfPants = 2.95;
            double priceOneDress = 4.55;
            double salestaxRate = 0.0575; // 5.75%
    
            string customerName = "James Burreck",
                   homePhone = "(202) 301-7030";
            int    numberOfShirts = 5,
                   numberOfPants = 2,
                   numberOfDresses = 3;
            int    totalNumberOfItems;
            double subTotalShirts, subTotalPants, subTotalDresses;
            double taxAmount, totalOrder, netPrice;
            int    orderMonth = 3, orderDay = 15, orderYear = 2002;
    
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
            subTotalShirts = priceOneShirt * numberOfShirts;
            subTotalPants = priceAPairOfPants * numberOfPants;
            subTotalDresses = numberOfDresses * priceOneDress;
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
            taxAmount = totalOrder * salestaxRate;
            netPrice = totalOrder - taxAmount;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("====================================");
            System.Console.Write("Customer:   ");
            System.Console.WriteLine(customerName);
            System.Console.Write("Home Phone: ");
            System.Console.WriteLine(homePhone);
            System.Console.Write("Order Date: ");
            System.Console.Write(orderMonth);
            System.Console.Write("/");
            System.Console.Write(orderDay);
            System.Console.Write("/");
            System.Console.WriteLine(orderYear);
            System.Console.WriteLine("------------------------------------");
            System.Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Shirts      ");
            System.Console.Write(numberOfShirts);
            System.Console.Write("     ");
            System.Console.Write(priceOneShirt);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalShirts);
            System.Console.Write("Pants       ");
            System.Console.Write(numberOfPants);
            System.Console.Write("     ");
            System.Console.Write(priceAPairOfPants);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalPants);
            System.Console.Write("Dresses     ");
            System.Console.Write(numberOfDresses);
            System.Console.Write("     ");
            System.Console.Write(priceOneDress);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalDresses);
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Number of Items: ");
            System.Console.WriteLine(totalNumberOfItems);
            System.Console.Write("Total Order:     ");
            System.Console.WriteLine(totalOrder);
            System.Console.Write("Tax Rate:        ");
            System.Console.Write(salestaxRate * 100);
            System.Console.WriteLine("%");
            System.Console.Write("Tax Amount:      ");
            System.Console.WriteLine(taxAmount);
            System.Console.Write("Net Price:       ");
            System.Console.WriteLine(netPrice);
            System.Console.WriteLine("====================================");
        }
    }
  2. Execute the program. This would produce:
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Number of Items: 10
    Total Order:     24.30
    Tax Rate:        5.7500%
    Tax Amount:      1.397250
    Net Price:       22.902750
    ====================================
  3. Close the DOS window and return to your programming environment

Introduction to the Division Operation

Dividing an item means cutting it in pieces or fractions of a set value. For example, when you cut an apple in the middle, you are dividing it in 2 pieces. If you cut each one of the resulting pieces, you will get 4 pieces or fractions. This is considered that you have divided the apple in 4 parts. Therefore, the division is used to get the fraction of one number in terms of another. The division is performed with the forward slash /. Here is an example:

class Exercise
{
    static void Main()
    {
		// Initializing various variables when declaring them with the same data type
		double value1 = 224.58, value2 = 1548.26;
		double result = value1 / value2;
			
		System.Console.Write(value1);
		System.Console.Write(" / ");
		System.Console.Write(value2);
		System.Console.Write(" = ");
		System.Console.WriteLine(result);
		System.Console.WriteLine();
    }
}

This would produce:

224.58 / 1548.26 = 0.145053156446592

Press any key to continue . . .

When performing the division, be aware of its many rules. Never divide by zero (0). Make sure that you know the relationship(s) between the numbers involved in the operation.

Practical LearningPractical Learning: Using the Division Operator

  1. To use the division, change the file as follows:
    class Exerise
    {
        static void Main()
        {
            double priceOneShirt = 0.95;
            double priceAPairOfPants = 2.95;
            double priceOneDress = 4.55;
            double discountRate = 0.20; // 20%
            double taxRate = 5.75;  // 5.75%
    
            string customerName = "James Burreck",
                   homePhone = "(202) 301-7030";
            int    numberOfShirts = 5,
                   numberOfPants = 2,
                   numberOfDresses = 3;
            int    totalNumberOfItems;
            double subTotalShirts, subTotalPants, subTotalDresses;
            double DiscountAmount, totalOrder, netPrice, taxAmount, salesTotal;
            double amountTended, difference;
            int    orderMonth = 3, orderDay = 15, orderYear = 2002;
    
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
            subTotalShirts = priceOneShirt * numberOfShirts;
            subTotalPants = priceAPairOfPants * numberOfPants;
            subTotalDresses = numberOfDresses * priceOneDress;
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
            DiscountAmount = totalOrder * discountRate;
            netPrice = totalOrder - DiscountAmount;
            taxAmount = totalOrder * taxRate / 100;
            salesTotal = netPrice + taxAmount;
            amountTended = 50;
            difference = amountTended - salesTotal;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("====================================");
            System.Console.Write("Customer:   ");
            System.Console.WriteLine(customerName);
            System.Console.Write("Home Phone: ");
            System.Console.WriteLine(homePhone);
            System.Console.Write("Order Date: ");
            System.Console.Write(orderMonth);
            System.Console.Write("/");
            System.Console.Write(orderDay);
            System.Console.Write("/");
            System.Console.WriteLine(orderYear);
            System.Console.WriteLine("------------------------------------");
            System.Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Shirts      ");
            System.Console.Write(numberOfShirts);
            System.Console.Write("     ");
            System.Console.Write(priceOneShirt);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalShirts);
            System.Console.Write("Pants       ");
            System.Console.Write(numberOfPants);
            System.Console.Write("     ");
            System.Console.Write(priceAPairOfPants);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalPants);
            System.Console.Write("Dresses     ");
            System.Console.Write(numberOfDresses);
            System.Console.Write("     ");
            System.Console.Write(priceOneDress);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalDresses);
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Number of Items: ");
            System.Console.WriteLine(totalNumberOfItems);
            System.Console.Write("Total Order:     ");
            System.Console.WriteLine(totalOrder);
            System.Console.Write("Discount Rate:   ");
            System.Console.Write(discountRate * 100);
            System.Console.WriteLine("%");
            System.Console.Write("Discount Amount: ");
            System.Console.WriteLine(DiscountAmount);
            System.Console.Write("After Discount:  ");
            System.Console.WriteLine(netPrice);
            System.Console.Write("Tax Rate:        ");
            System.Console.Write(taxRate);
            System.Console.WriteLine("%");
            System.Console.Write("Tax Amount:      ");
            System.Console.WriteLine(taxAmount);
            System.Console.Write("Net Price:       ");
            System.Console.WriteLine(salesTotal);
            System.Console.WriteLine("====================================");
            System.Console.Write("Amount Tended:   ");
            System.Console.WriteLine(amountTended);
            System.Console.Write("Difference:      ");
            System.Console.WriteLine(difference);
            System.Console.WriteLine("====================================");
        }
    }
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Number of Items: 10
    Total Order:     24.30
    Discount Rate:   20.00%
    Discount Amount: 4.8600
    After Discount:  19.4400
    Tax Rate:        5.75%
    Tax Amount:      1.39725
    Net Price:       20.83725
    ====================================
    Amount Tended:   50
    Difference:      29.16275
    ====================================
  3. Close the DOS window and return to your programming environment

Introduction to Value Conversion

Introduction

Sometimes a value will be provided to you but you may not know in advance what that value looks like. If you are planning to use, such as to display or involve, such a value in an operation, you may first need to analyze that value and then convert it to the desired type. Fortunately, C# (including the .NET Framework, and we will learn that you can use the Visual Basic language in your C# code) is equipped to assist you in analyzing and converting a value to a number, a string, or else.

Practical LearningPractical Learning: Introducing Value Conversion

  1. Change the document as follows:
    class Order
    {
        static void Main()
        {
            double priceOneShirt = 1.2;
            double priceAPairOfPants = 2.3;
            double priceOneDress = 3.5;
            double discountRate = 0.125; // 12.50%
            double taxRate = 6.15;  // 6.15%
    
            string customerName = "Jason Becker",
                   homePhone = "(571) 397-5940";
            int numberOfShirts = 5,
                   numberOfPants = 2,
                   numberOfDresses = 3;
            int totalNumberOfItems;
            double subTotalShirts, subTotalPants, subTotalDresses;
            double discountAmount, totalOrder, netPrice, taxAmount, salesTotal;
            double amountTended, difference;
            int orderMonth = 10, orderDay = 15, orderYear = 2020;
    
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
            subTotalShirts = priceOneShirt * numberOfShirts;
            subTotalPants = priceAPairOfPants * numberOfPants;
            subTotalDresses = numberOfDresses * priceOneDress;
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
            discountAmount = totalOrder * discountRate;
            netPrice = totalOrder - discountAmount;
            taxAmount = totalOrder * taxRate / 100;
            salesTotal = netPrice + taxAmount;
            amountTended = 20;
            difference = amountTended - salesTotal;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("====================================");
            System.Console.Write("Customer:   ");
            System.Console.WriteLine(customerName);
            System.Console.Write("Home Phone: ");
            System.Console.WriteLine(homePhone);
            System.Console.Write("Order Date: ");
            System.Console.Write(orderMonth);
            System.Console.Write('/');
            System.Console.Write(orderDay);
            System.Console.Write('/');
            System.Console.WriteLine(orderYear);
            System.Console.WriteLine("------------------------------------");
            System.Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Shirts      ");
            System.Console.Write(numberOfShirts);
            System.Console.Write("     ");
            System.Console.Write(priceOneShirt);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalShirts);
            System.Console.Write("Pants       ");
            System.Console.Write(numberOfPants);
            System.Console.Write("     ");
            System.Console.Write(priceAPairOfPants);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalPants);
            System.Console.Write("Dresses     ");
            System.Console.Write(numberOfDresses);
            System.Console.Write("     ");
            System.Console.Write(priceOneDress);
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalDresses);
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Number of Items: ");
            System.Console.WriteLine(totalNumberOfItems);
            System.Console.Write("Total Order:     ");
            System.Console.WriteLine(totalOrder);
            System.Console.Write("Discount Rate:   ");
            System.Console.Write(discountRate * 100);
            System.Console.WriteLine('%');
            System.Console.Write("Discount Amount: ");
            System.Console.WriteLine(discountAmount);
            System.Console.Write("After Discount:  ");
            System.Console.WriteLine(netPrice);
            System.Console.Write("Tax Rate:        ");
            System.Console.Write(taxRate);
            System.Console.WriteLine('%');
            System.Console.Write("Tax Amount:      ");
            System.Console.WriteLine(taxAmount);
            System.Console.Write("Net Price:       ");
            System.Console.WriteLine(salesTotal);
            System.Console.WriteLine("====================================");
            System.Console.Write("Amount Tended:   ");
            System.Console.WriteLine(amountTended);
            System.Console.Write("Difference:      ");
            System.Console.WriteLine(difference);
            System.Console.WriteLine("====================================");
        }
    }
  2. To execute the program, on the main menu, click Debug -> Start Without Debugging:
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   Jason Becker
    Home Phone: (571) 397-5940
    Order Date: 10/15/2020
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     1.2     6
    Pants       2     2.3     4.6
    Dresses     3     3.5     10.5
    ------------------------------------
    Number of Items: 10
    Total Order:     21.1
    Discount Rate:   12.5%
    Discount Amount: 2.6375
    After Discount:  18.4625
    Tax Rate:        6.15%
    Tax Amount:      1.29765
    Net Price:       19.76015
    ====================================
    Amount Tended:   20
    Difference:      0.239849999999997
    ====================================
    Press any key to continue . . .
  3. Press any key yo close the DOS window and return to your programming environment

Converting a Value to an Integer

Most of the values that will be provided to you in an application are strings or else. If you expect such a value to be a natural number and you plan to use that number in an operation, you should first convert that value to an integer. The primary formula to follow is:

int.Parse(value-to-convert);

In this case, in the parentheses of int.Parse(), enter the value you want to convert. If the value can be appropriately and safely converted, int.Parse() will produce that value. You can then display that value using System.Console.Write() System.Console.WriteLine(). To do that, you can write the int.Parse(value-to-convert); expression in the parentheses of System.Console.Write() or of System.Console.WriteLine(). Here is as example:

class Order
{
    static void Main()
    {
        string yearlySalary = "58508";

        System.Console.Write("Yearly Salary: ");

        System.Console.Write(int.Parse(yearlySalary));

        System.Console.WriteLine();
    }
}

In some cases, you may want to store the converted value in a variable. The formula you can follow is:

variable-name = int.Parse(value-to-convert);

You can then display the value using System.Console.Write() System.Console.WriteLine(). Here is as example:

class Order
{
    static void Main()
    {
        string yearlySalary = "58508";
        int result = int.Parse(yearlySalary);

        System.Console.Write("Yearly Salary: ");
        System.Console.WriteLine(result);
    }
}

Converting a Value to a String

In our introduction to values, we have seen that an operation can produce various types of values. Some values cannot be directly displayed to the user. One way to address this issue is to first convert a valu to a string and then display it. First, to convert a value to a string, you can declare a string variable and assign an expression to it. The formula to follow is:

variable = value-to-format.ToString()

Here is an example:

class Order
{
    static void Main()
    {
        int monthlySalary = 3288;

        string result = monthlySalary.ToString();

        System.Console.Write("Monthly Salary: ");
        System.Console.WriteLine(result);
    }
}

If you simply want to display a value in your application, you can write the value-to-format.ToString() expression directly in the parentheses of System.Console.Write() or of System.Console.WriteLine(). Here are examples:

class Order
{
    static void Main()
    {
        int monthlySalary = 3288;

        System.Console.Write("Monthly Salary: ");
        System.Console.WriteLine(monthlySalary.ToString(););
    }
}

Formatting a Value to Display

By now, we know that an operation can produce a value thay is not the way you want to present to the user. Fortunately, C# (including the .NET Framework and Visual Basic) can assist you in formatting a number in a suitable manner. If you want to display a value in a format known as Fixed, in the parentheses of value-to-format.ToString(), type "F".

The issues related to value display and number formatting are larger than what we have introduced in this lesson. In later lessons, we will discuss those issues more.

Practical LearningPractical Learning: Introducing Decimal Numbers

  1. Change the document as follows:
    class Order
    {
        static void Main()
        {
            double priceOneShirt     = 1.2;
            double priceAPairOfPants = 2.3;
            double priceOneDress     = 3.5;
            double discountRate      = 0.125; // 12.50%
            double taxRate           = 6.15;  // 6.15%
    
            string customerName    = "Jason Becker",
                   homePhone       = "(571) 397-5940";
            int numberOfShirts     = 5,
                   numberOfPants   = 2,
                   numberOfDresses = 3;
            int totalNumberOfItems;
            double subTotalShirts, subTotalPants, subTotalDresses;
            double discountAmount, totalOrder, netPrice, taxAmount, salesTotal;
            double amountTended, difference;
            int orderMonth = 10, orderDay = 15, orderYear = 2020;
    
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
            subTotalShirts = priceOneShirt * numberOfShirts;
            subTotalPants = priceAPairOfPants * numberOfPants;
            subTotalDresses = numberOfDresses * priceOneDress;
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
            discountAmount = totalOrder * discountRate;
            netPrice = totalOrder - discountAmount;
            taxAmount = totalOrder * taxRate / 100;
            salesTotal = netPrice + taxAmount;
            amountTended = 20;
            difference = amountTended - salesTotal;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("====================================");
            System.Console.Write("Customer:   ");
            System.Console.WriteLine(customerName);
            System.Console.Write("Home Phone: ");
            System.Console.WriteLine(homePhone);
            System.Console.Write("Order Date: ");
            System.Console.Write(orderMonth);
            System.Console.Write('/');
            System.Console.Write(orderDay);
            System.Console.Write('/');
            System.Console.WriteLine(orderYear);
            System.Console.WriteLine("------------------------------------");
            System.Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Shirts      ");
            System.Console.Write(numberOfShirts);
            System.Console.Write("     ");
            System.Console.Write(priceOneShirt.ToString("F"));
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalShirts.ToString("F"));
            System.Console.Write("Pants       ");
            System.Console.Write(numberOfPants);
            System.Console.Write("     ");
            System.Console.Write(priceAPairOfPants.ToString("F"));
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalPants.ToString("F"));
            System.Console.Write("Dresses     ");
            System.Console.Write(numberOfDresses);
            System.Console.Write("     ");
            System.Console.Write(priceOneDress.ToString("F"));
            System.Console.Write("     ");
            System.Console.WriteLine(subTotalDresses.ToString("F"));
            System.Console.WriteLine("------------------------------------");
            System.Console.Write("Number of Items: ");
            System.Console.WriteLine(totalNumberOfItems);
            System.Console.Write("Total Order:     ");
            System.Console.WriteLine(totalOrder.ToString("F"));
            System.Console.Write("Discount Rate:   ");
            System.Console.Write(discountRate * 100);
            System.Console.WriteLine('%');
            System.Console.Write("Discount Amount: ");
            System.Console.WriteLine(discountAmount.ToString("F"));
            System.Console.Write("After Discount:  ");
            System.Console.WriteLine(netPrice.ToString("F"));
            System.Console.Write("Tax Rate:        ");
            System.Console.Write(taxRate);
            System.Console.WriteLine('%');
            System.Console.Write("Tax Amount:      ");
            System.Console.WriteLine(taxAmount.ToString("F"));
            System.Console.Write("Net Price:       ");
            System.Console.WriteLine(salesTotal.ToString("F"));
            System.Console.WriteLine("====================================");
            System.Console.Write("Amount Tended:   ");
            System.Console.WriteLine(amountTended);
            System.Console.Write("Difference:      ");
            System.Console.WriteLine(difference.ToString("F"));
            System.Console.WriteLine("====================================");
        }
    }
  2. To execute the program, on the main menu, click Debug -> Start Without Debugging:
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   Jason Becker
    Home Phone: (571) 397-5940
    Order Date: 10/15/2020
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     1.20     6.00
    Pants       2     2.30     4.60
    Dresses     3     3.50     10.50
    ------------------------------------
    Number of Items: 10
    Total Order:     21.10
    Discount Rate:   12.5%
    Discount Amount: 2.64
    After Discount:  18.46
    Tax Rate:        6.15%
    Tax Amount:      1.30
    Net Price:       19.76
    ====================================
    Amount Tended:   20
    Difference:      0.24
    ====================================
    Press any key to continue . . .
  3. To close the DOS window and return to your programming environment, press any key
  4. Close Microsoft Visual Studio

Previous Copyright © 2001-2021, FunctionX Next