Fundamental C# Operators

Introduction to Operators

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.

Introduction to Unary Operators

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 and, in the Visual Studio 2022 dialog box, click Create a New Project (if Microsoft Visual Studio is already opened, to create a new application, on the main menu, click File -> New -> Project...)
  2. In the right list of projects templates, click Console App.
    Click Next
  3. Change the Project Name to GeorgetownDryCleaningServices2 and accept or change the project Location
  4. Click Next
  5. In the Additional Information dialog box, make sure the Framework combo box is displaying .NET 8.0 (Long-Term Support).
    Click Create

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:

using static System.Console;

{
}

Parentheses: ( and )

Parentheses are used to isolate a group of items that must be considered as belonging to one entity. Here is an example:

using static System.Console;

static void Main()

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

The Semicolon ;

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:

using static System.Console;

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:

variable-name = Value

The variable-name 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:

using static System.Console;

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:

using static System.Console;

double salary;

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

This would produce:

Employee's Hourly Salary: $12.55
Press any key to close this window . . .

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:

using static System.Console;

// Using the assignment operator
double salary = 12.55;

Write("Employee's Hourly Salary: ");
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:

using static System.Console;

// Initializing various variables when declaring them with the same data type
double value1 = 224.58, value2 = 1548.26;
			
Write("Value 1 = ");
WriteLine(value1);
Write("Value 2 = ");
WriteLine(value2);
WriteLine();

This would produce:

Value 1 = 224.58
Value 2 = 1548.26
Press any key to close this window . . .

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:

using static 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. Change the document as follows:
    using static System.Console;
    
    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%;
    
    WriteLine("-/-Georgetown Cleaning Services -/-");
    WriteLine("===================================");
    
    Write("Customer:   ");
    WriteLine(customerName);
    Write("Home Phone: ");
    WriteLine(homePhone);
    Write("Order Date: ");
    Write(orderMonth);
    Write('/');
    Write(orderDay);
    Write('/');
    WriteLine(orderYear);
    WriteLine("-----------------------------------");
    WriteLine("Item Type  Qty Sub-Total");
    WriteLine("------------------------");
    Write("Shirts      ");
    Write(numberOfShirts);
    Write("     ");
    WriteLine(priceOneShirt);
    Write("Pants       ");
    Write(numberOfPants);
    Write("     ");
    WriteLine(priceAPairOfPants);
    Write("Dresses     ");
    Write(numberOfDresses);
    Write("     ");
    WriteLine(priceOneDress);
    WriteLine("-----------------------------------");
    Write("Monday Discount: ");
    Write(mondayDiscount);
    WriteLine('%');
    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 close this window . . .
  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:

using static System.Console;

// Displaying an unsigned number
Write("Number = ");
WriteLine(+802);

This would produce:

Number = 802
Press any key to close this window . . .

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:

using static System.Console;

// Displaying an unsigned number
Write("First Number  ");
WriteLine(+802);
// Displaying a negative number
Write("Second Number ");
WriteLine(-802);

This would produce:

First Number  802
Second Number -802
Press any key to close this window . . .

The Addition Operations

Introduction

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:

using static System.Console;

Write("244 + 835 = ");
WriteLine(244 + 835);

Here is the result:

244 + 835 = 1079
Press any key to close this window . . .

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 document as follows:
    using static System.Console;
    
    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;
    
    WriteLine("-/- Georgetown Cleaning Services -/-");
    WriteLine("========================");
    Write("Customer:   ");
    WriteLine(customerName);
    Write("Home Phone: ");
    WriteLine(homePhone);
    Write("Order Date: ");
    Write(orderMonth);
    Write("/");
    Write(orderDay);
    Write("/");
    WriteLine(orderYear);
    WriteLine("------------------------");
    WriteLine("Item Type  Qty Sub-Total");
    WriteLine("------------------------");
    Write("Shirts      ");
    Write(numberOfShirts);
    Write("     ");
    WriteLine(priceOneShirt);
    Write("Pants       ");
    Write(numberOfPants);
    Write("     ");
    WriteLine(priceAPairOfPants);
    Write("Dresses     ");
    Write(numberOfDresses);
    Write("     ");
    WriteLine(priceOneDress);
    WriteLine("------------------------");
    Write("Number of Items: ");
    WriteLine(totalNumberOfItems);
    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
    ========================
    Press any key to close this window . . .
  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:

using static System.Console;

string firstName = "Alexander";
string lastName  = "Kallack";
string fullName  = firstName + " " + lastName;

Write("Full Name: ");
WriteLine(fullName);

This would produce:

Full Name: Alexander Kallack
Press any key to close this window . . .

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:

using static System.Console;

double rate = 17.82;
string salary = "Hourly Salary: ";

string result = salary + rate;

WriteLine(result);

Embedding an Operation

We already know that, to display a value, you can put it in the parentheses of Write() or 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 WriteLine():

using static 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:

using static System.Console;

string mainTitle = "Red Oak High School";
string subTitle  = "Students Records";

Write(mainTitle + " - " + subTitle);

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

using static System.Console;

string salary = "Hourly Salary: ";
double rate = 17.82;

WriteLine(salary + rate);

Incrementing a Variable

Introduction

We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. The simplest technique of incrementing a value consists of adding 1 to it. You can apply this feature in computer programming. To do this, first declare a variable. Add 1 to that variable, and assign the result to the variable itself. This is illustrated in the following example:

using static System.Console;

// This program studies value incrementing

int value = 12;

WriteLine("Techniques of incrementing a value");
Write("Value = ");
WriteLine(value);

value = value + 1;

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of incrementing a value
Value = 12
Value = 13
Press any key to close this window . . .

C# provides a special operator that takes care of this operation. The operator is called the increment operator and is represented by ++. Instead of writing value = value + 1, you can write value++ and you would get the same result. The above program can be re-written as follows:

using static System.Console;

// This program studies value incrementing

int value = 12;

WriteLine("Techniques of incrementing a value");
Write("Value = ");
WriteLine(value);

value++;

Write("Value = ");
WriteLine(value);

The ++ is a unary operator because it operates on only one variable. It is used to modify the value of the variable by adding 1 to it. Every time the Value++ is executed, the compiler takes the previous value of the variable, adds 1 to it, and the variable holds the incremented value:

using static System.Console;

// This program studies value incrementing

int value = 12;

WriteLine("Techniques of incrementing a value");

value++;
	
Write("Value = ");
WriteLine(value);

value++;
	
Write("Value = ");
WriteLine(value);

Value++;

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of incrementing a value
Value = 13
Value = 14
Value = 15
Press any key to close this window . . .

Pre and Post-Increment

When using the ++ operator, the position of the operator with regard to the variable it is modifying can be significant. To increment the value of the variable before re-using it, you should position the operator on the left of the variable:

using static System.Console;

// This program studies value incrementing

int value = 12;

WriteLine("Techniques of incrementing a value");

Write("Value = ");
WriteLine(value);

Write("Value = ");
WriteLine(++value);

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of incrementing a value
Value = 12
Value = 13
Value = 13
Press any key to close this window . . .

When writing ++Value, the value of the variable is incremented before being called. On the other hand, if you want to first use a variable, then increment it, in other words, if you want to increment the variable after calling it, position the increment operator on the right side of the variable:

using static System.Console;

// This program studies value incrementing

int value = 12;

WriteLine("Techniques of incrementing a value");

Write("Value = ");
WriteLine(value);

Write("Value = ");
WriteLine(value++);

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of incrementing a value
Value = 12
Value = 12
Value = 13
Press any key to close this window . . .

Compound Addition

Introduction

It is not unusual to add a constant value to a variable. All you have to do is to declare another variable that would hold the new value. Here is an example:

using static System.Console;

// This program studies value incrementing and decrementing

double value = 12.75;
double newValue;

WriteLine("Techniques of incrementing and decrementing a value");
Write("Value = ");
WriteLine(value);

newValue = value + 2.42;
		
Write("Value = ");
WriteLine(newValue);

This would produce:

Techniques of incrementing and decrementing a value
Value = 12.75
Value = 15.17
Press any key to close this window . . .

The above technique requires that you use an extra variable in your application. The advantage is that each value can hold its own value although the value of the second variable depends on whatever would happen to the original or source variable. Sometimes in your program you will not need to keep the original value of the source variable. You may want to permanently modify the value that a variable is holding. In this case, you can perform the addition operation directly on the variable by adding the desired value to the variable. This operation modifies whatever value a variable is holding and does not need an additional variable.

To add a value to a variable and change the value that the variable is holding, you can combine the assignment "=" and the addition "+" operators to produce a new operator as +=. Here is an example:

using static System.Console;

// This program studies value incrementing and decrementing

double value = 12.75;

WriteLine("Techniques of incrementing and decrementing a value");
Write("Value = ");
WriteLine(value);

value += 2.42;
		
Write("Value = ");
WriteLine(value);

This program produces the same result as the previous. You can also perform a post-increment operation on variables. Here is an example:

using static System.Console;

double value = 12.75;
int nbr = 3;

WriteLine("Techniques of incrementing and decrementing a value");
WriteLine($"Value = {value}");

value += nbr;

Write("Value = ");
WriteLine($"Value = {value}");

This would produce:

Techniques of incrementing and decrementing a value
Value = 12.75
Value = Value = 15.75

Press any key to close this window . . .

Compound Addition and Strings

Imagine you want to combine two strings to get a new string. Here are examples:

string name = "Jim";
name = name + "my";

This would produce:

Jimmy

Instead of, or besides, the regular addition, you can use the compound addition, practically the same way it is used for numbers. Here is an example:

string name = "Jim";
name += "my";

The Multiplication Operation

Introduction

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:

using static System.Console;

// Initializing various variables when declaring them with the same data type
double value1 = 224.58, value2 = 1548.26;
double result = value1 * value2;

Write(value1);
Write(" * ");
Write(value2);
Write(" = ");
WriteLine(result);
WriteLine();

This would produce:

224.58 * 1548.26 = 347708.2308

Press any key to close this window . . .

Practical LearningPractical Learning: Using the Multiplication Operator

  1. To multiply, change the document as follows:
    using static System.Console;
    
    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;
    
    WriteLine("-/- Georgetown Cleaning Services -/-");
    WriteLine("====================================");
    Write("Customer:   ");
    WriteLine(customerName);
    Write("Home Phone: ");
    WriteLine(homePhone);
    Write("Order Date: ");
    Write(orderMonth);
    Write("/");
    Write(orderDay);
    Write("/");
    WriteLine(orderYear);
    WriteLine("------------------------------------");
    WriteLine("Item Type  Qty Unit/Price Sub-Total");
    WriteLine("------------------------------------");
    Write("Shirts      ");
    Write(numberOfShirts);
    Write("     ");
    Write(priceOneShirt);
    Write("     ");
    WriteLine(subTotalShirts);
    Write("Pants       ");
    Write(numberOfPants);
    Write("     ");
    Write(priceAPairOfPants);
    Write("     ");
    WriteLine(subTotalPants);
    Write("Dresses     ");
    Write(numberOfDresses);
    Write("     ");
    Write(priceOneDress);
    Write("     ");
    WriteLine(subTotalDresses);
    WriteLine("------------------------------------");
    Write("Number of Items: ");
    WriteLine(totalNumberOfItems);
    Write("Total Order:     ");
    WriteLine(totalOrder);
    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
    ====================================
    Press any key to close this window . . .
  3. Close the DOS window and return to your programming environment

Compound Multiplication

You can multiply a value by a variable and assign the result to the same variable. Here is an example:

using static System.Console;

double value = 12.75;

Write("Value = ");
WriteLine(value);

value = value * 2.42;

Write("Value = ");
WriteLine(value);

This would produce:

Value = 12.75
Value = 30.855
Press any key to close this window . . .

To make this operation easy, the C# language supports the compound multiplication assignment operator represented as *=. To use it, use the *= operator and assign the desired value to the variable. Here is an example:

using static System.Console;

double value = 12.75;

Write("Value = ");
WriteLine(value);

value *= 2.42;

Write("Value = ");
WriteLine(value);

The Subtraction Operations

Introduction

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:

using static System.Console;

// Values used in this program
double value1 = 224.58, value2 = 1548.26;
double result = value1 - value2;

Write(value1);
Write(" - ");
Write(value2);
Write(" = ");
WriteLine(result);

This would produce:

224.58 - 1548.26 = -1323.68

Press any key to close this window . . .

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:

using static System.Console;

// This tests whether the addition is associative
WriteLine(" =+= Addition =+=");
Write("128 + 42 +   5 = ");
WriteLine(128 + 42 + 5);
Write("  5 + 42 + 128 = ");
WriteLine(5 + 42 + 128);
	
WriteLine();

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

This would produce:

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

 =-= Subtraction =-=
128 - 42 -   5 = 81
  5 - 42 - 128 = -165
Press any key to close this window . . .

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:
    using static System.Console;
    
    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;
    
    WriteLine("-/- Georgetown Cleaning Services -/-");
    WriteLine("====================================");
    Write("Customer:   ");
    WriteLine(customerName);
    Write("Home Phone: ");
    WriteLine(homePhone);
    Write("Order Date: ");
    Write(orderMonth);
    Write("/");
    Write(orderDay);
    Write("/");
    WriteLine(orderYear);
    WriteLine("------------------------------------");
    WriteLine("Item Type  Qty Unit/Price Sub-Total");
    WriteLine("------------------------------------");
    Write("Shirts      ");
    Write(numberOfShirts);
    Write("     ");
    Write(priceOneShirt);
    Write("     ");
    WriteLine(subTotalShirts);
    Write("Pants       ");
    Write(numberOfPants);
    Write("     ");
    Write(priceAPairOfPants);
    Write("     ");
    WriteLine(subTotalPants);
    Write("Dresses     ");
    Write(numberOfDresses);
    Write("     ");
    Write(priceOneDress);
    Write("     ");
    WriteLine(subTotalDresses);
    WriteLine("------------------------------------");
    Write("Number of Items: ");
    WriteLine(totalNumberOfItems);
    Write("Total Order:     ");
    WriteLine(totalOrder);
    Write("Tax Rate:        ");
    Write(salestaxRate * 100);
    WriteLine("%");
    Write("Tax Amount:      ");
    WriteLine(taxAmount);
    Write("Net Price:       ");
    WriteLine(netPrice);
    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
    ====================================
    Press any key to close this window . . .
  3. Close the DOS window and return to your programming environment

Decrementing a Variable

When counting numbers backward, such as 8, 7, 6, 5, etc, we are in fact subtracting 1 from a value in order to get the lesser value. This operation is referred to as decrementing a value. This operation works as if a value is decremented by 1. Here is an example:

using static System.Console;

// This program studies value decrementing

int value = 12;

WriteLine("Techniques of decrementing a value");
Write("Value = ");
WriteLine(value);

value = value - 1;

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11
Press any key to close this window . . .

As done to increment, C# provides a quicker way of subtracting 1 from a value. This is done using the decrement operator, that is --. To use the decrement operator, type - on the left or the right side of the variable when this operation is desired. Using the decrement operator, the above program could be written:

using static System.Console;

// This program studies value decrementing

int value = 12;

WriteLine("Techniques of decrementing a value");
Write("Value = ");
WriteLine(value);

value--;

Write("Value = ");
WriteLine(value);

Pre-Decrementing a Value

Once again, the position of the operator can be important. If you want to decrement the variable before calling it, position the decrement operator on the left side of the operand. This is illustrated in the following program:

using static System.Console;

// This program studies value decrementing

int value = 12;

WriteLine("Techniques of decrementing a value");
Write("Value = ");
WriteLine(value);

Write("Value = ");
WriteLine(--value);

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11
Value = 11
Press any key to close this window . . .

If you plan to decrement a variable only after it has been accessed, position the operator on the right side of the variable. Here is an example:

using static System.Console;

// This program studies value decrementing

int value = 12;

WriteLine("Techniques of decrementing a value");
Write("Value = ");
WriteLine(value);

Write("Value = ");
WriteLine(Value--);

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of decrementing a value
Value = 12
Value = 12
Value = 11
Press any key to close this window . . .

Compound Subtraction

You may want to subtract a constant value from a variable. To decrement a value from a variable, use the subtraction and apply the same technique. This is done with the -= operator. Here is an example:

using static System.Console;

// This program studies value incrementing and decrementing

double value = 12.75;

WriteLine("Techniques of incrementing and decrementing a value");
Write("Value = ");
WriteLine(value);

value -= 2.42;

Write("Value = ");
WriteLine(value);

This would produce:

Techniques of incrementing and decrementing a value
Value = 12.75
Value = 10.33
Press any key to close this window . . .

The Division Operation

Introduction

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:

using static System.Console;

// Initializing various variables when declaring them with the same data type
double value1 = 224.58, value2 = 1548.26;
double result = value1 / value2;
			
Write(value1);
Write(" / ");
Write(value2);
Write(" = ");
WriteLine(result);
WriteLine();

This would produce:

224.58 / 1548.26 = 0.145053156446592

Press any key to close this window . . .

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:
    using static System.Console;
    
    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;
    
    WriteLine("-/- Georgetown Cleaning Services -/-");
    WriteLine("====================================");
    Write("Customer:   ");
    WriteLine(customerName);
    Write("Home Phone: ");
    WriteLine(homePhone);
    Write("Order Date: ");
    Write(orderMonth);
    Write("/");
    Write(orderDay);
    Write("/");
    WriteLine(orderYear);
    WriteLine("------------------------------------");
    WriteLine("Item Type  Qty Unit/Price Sub-Total");
    WriteLine("------------------------------------");
    Write("Shirts      ");
    Write(numberOfShirts);
    Write("     ");
    Write(priceOneShirt);
    Write("     ");
    WriteLine(subTotalShirts);
    Write("Pants       ");
    Write(numberOfPants);
    Write("     ");
    Write(priceAPairOfPants);
    Write("     ");
    WriteLine(subTotalPants);
    Write("Dresses     ");
    Write(numberOfDresses);
    Write("     ");
    Write(priceOneDress);
    Write("     ");
    WriteLine(subTotalDresses);
    WriteLine("------------------------------------");
    Write("Number of Items: ");
    WriteLine(totalNumberOfItems);
    Write("Total Order:     ");
    WriteLine(totalOrder);
    Write("Discount Rate:   ");
    Write(discountRate * 100);
    WriteLine("%");
    Write("Discount Amount: ");
    WriteLine(DiscountAmount);
    Write("After Discount:  ");
    WriteLine(netPrice);
    Write("Tax Rate:        ");
    Write(taxRate);
    WriteLine("%");
    Write("Tax Amount:      ");
    WriteLine(taxAmount);
    Write("Net Price:       ");
    WriteLine(salesTotal);
    WriteLine("====================================");
    Write("Amount Tended:   ");
    WriteLine(amountTended);
    Write("Difference:      ");
    WriteLine(difference);
    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
    ====================================
    Press any key to close this window . . .
  3. Close the DOS window and return to your programming environment

Compound Division

Remember that you can add, subtract, or multiply a value to a variable and assign the result to the variable itself. You can also perform this operation using the division. Here is an example:

using static System.Console;

double value = 12.75;

Write("Value = ");
WriteLine(value);

value = value / 2.42;

Write("Value = ");
WriteLine(value);

This would produce:

Value = 12.75
Value = 5.26859504132231
Press any key to close this window . . .

To perform this operation faster, the C# language provides the /= operator. Here is an example of using it:

using static System.Console;

double value = 12.75;

Write("Value = ");
WriteLine(value);

value /= 2.42;

Write("Value = ");
WriteLine(value);

The Remainder

Introduction

The division program gives a result of a number with decimal values if you provide an odd number (like 147), which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result. Imagine you have 26 kids at a football (soccer) stadium and they are about to start. You know that you need 11 kids for each team to start. If the game starts with the right amount of players, how many will seat and wait?

The remainder operation is performed with the percent sign (%) which is gotten from pressing Shift + 5.

Here is an example:

using static System.Console;

int players = 18;
int remainder = players % 11;

// When the game starts, how many players will wait?.
Write("Out of ");
Write(players);
Write(" players, ");
Write(remainder);
WriteLine(" players will have to wait when the game starts.\n");

This would produce:

Out of 18 players, 7 players will have to wait when the game starts.

Press any key to close this window . . .

The Compound Remainder

As seen with the other arithmetic operators, you can find the remainder of a variable and assign the result to the variable itself. Here is an example:

using static System.Console;

int players = 18;

// When the game starts, how many players will wait?.
Write("Out of ");
Write(players);
Write(" players, ");

players = players % 11;
    
Write(players);
WriteLine(" players will have to wait when the game starts.\n");

To support a faster version of this operation, the C# language provides the compound remainder operator represented as %=. To use it, assign its value to the variable. Here is an example:

using static System.Console;

int Players = 18;

// When the game starts, how many players will wait?.
Write("Out of ");
Write(players);
Write(" players, ");

players %= 11;
 
Write(players);
WriteLine(" players will have to wait when the game starts.\n");

Options on Declaring and Managing Variables

A Variable With a Keyword Name

As mentioned previously, you must avoid using keywords to name your variables. If you have to violate that rule, that is, if you want to use a keyword as the name of a variable, start the name of the variable with the @ sign. Here are examples:

using static System.Console;

int @double = 3648;
double @static = 248.59;
string @class = "Nuclear Energy";

After declaring a variable with an @name, you can use the variable but make sure you always use the @symbol on its name. Here are examples:

using static System.Console;

int    @double = 3648;
double @static = 248.59;
string @class  = "Nuclear Energy";

WriteLine("Values");
WriteLine("-------------------------");
Write("Distance: ");
Write(@double);
WriteLine(" miles");
Write("Net Pay:  ");
WriteLine(@static);
Write("Industry: ");
WriteLine(@class);

WriteLine("==================================");

This would produce:

Values
-------------------------
Distance: 3648 miles
Net Pay:  248.59
Industry: Nuclear Energy
==================================
Press any key to close this window . . .

Even if you use variable names that don't use C# keywords, you can start the name of any variable with the @ symbol. Here are examples:

using static System.Console;

string @description = "Short Sleeve Shirt";
int @quantity = 26;
string @size = "Medium";
double @unitPrice = 8.85;

When accessing the variable, if you want, you can start the name of the variable with the @ symbol or you can omit the @ symbol. Here are examples:

using static System.Console;

string @description = "Short Sleeve Shirt";
int    @quantity    = 26;
string @size        = "Medium";
double @unitPrice   = 8.85;

WriteLine("School Uniform");
WriteLine("------------------------------");
Write("Item Name:  ");
WriteLine(@description);
Write("Item Size:  ");
WriteLine(size);
Write("Quantity:   ");
WriteLine(@quantity);
Write("Unit Price: ");
WriteLine(unitPrice);
WriteLine("===============================");

This would produce:

School Uniform
------------------------------
Item Name:  Short Sleeve Shirt
Item Size:  Medium
Quantity:   26
Unit Price: 8.85
===============================
Press any key to close this window . . .

Even if you declare a variable whose name doesn't use a keyword, when accessing the variable, you can start its name with or without the @ symbol. If you decide to start a name with the @ symbol, you can use only one @ symbol on the name. Here are examples:

using static System.Console;

double areaGuam = 570.62;
double areaAlaska = 665_384.04;
double areaSouthDakota = 77115.68;
double areaTennessee = 42_144.25;

WriteLine("States Areas");
WriteLine("=======================");
Write("Guam: ");
WriteLine(@areaGuam);
Write("Alaska: ");
WriteLine(areaAlaska);
Write("Tennessee: ");
WriteLine(@areaTennessee);
Write("South Dakota: ");
WriteLine(areaSouthDakota);

This would produce:

States Areas
_________________________
Guam: 570.62
Alaska: 665384.04
Tennessee: 42144.25
South Dakota: 77115.68
============================
Press any key to close this window . . .

Updating a Variable

When declaring a variable, you don't have to initialize it. This means that you can declare a variable, perform other operations, and then on another line, specify the value of the variable. The rule to observe is that, if you decide to display the value of the variable, you must first specify its value. This can be done as follow:

using static System.Console;

data-type variable-name;

// Optionally do other things here...

variable-name = desired-value;

Here are examples:

using static System.Console;

string fullName;
double hourlySalary;

WriteLine("Employee Details");
WriteLine("=======================");

hourlySalary = 22.27;
fullName = "Martial Engolo";

Write("Employee Name: ");
WriteLine(fullName);
Write("Houly Rate: ");
WriteLine(hourlySalary);

This would produce:

Employee Details
=======================
Employee Name: Martial Engolo
Houly Rate: 22.27
Press any key to close this window . . .

Still, you can initialize a variable, perform other operations, and then specify a new value for the variable. This means that, at any time, you can change the value of a variable. This is also referred to as updating the variable. When you update a variable, its previous value is lost and it assumes the new value. Here are examples:

using static System.Console;

string fullName = "Martial Engolo";
double hourlySalary = 22.27;

WriteLine("Employee Details");
WriteLine("=======================");
Write("Employee Name: ");
WriteLine(fullName);
Write("Hourly Rate: ");
WriteLine(hourlySalary);

hourlySalary = 35.08;
fullName = "Annette Sandt";

WriteLine("----------------------");
Write("Employee Name: ");
WriteLine(fullName);
Write("Hourly Rate: ");
WriteLine(hourlySalary);

This would produce:

Employee Details
=======================
Employee Name: Martial Engolo
Hourly Rate: 22.27
----------------------
Employee Name: Annette Sandt
Hourly Rate: 35.08
Press any key to close this window . . .

Declaring Many Variables

As we have seen so far, you can declare as many variables as you want. Here are examples:

using static System.Console;

string status = "Full Time";
string firstName = "Martial";
double hourlySalary = 22.27;
string lastName = "Engolo";
double timeWorked = 42.50;

WriteLine("Employee Details");
WriteLine("============================");
Write("Employee Name: ");
Write(firstName);
Write(" ");
WriteLine(lastName);
Write("Status: ");
WriteLine(status);
Write("Hourly Rate: ");
WriteLine(hourlySalary);
Write("Time Worked: ");
WriteLine(timeWorked);

This would produce:

Employee Details
============================
Employee Name: Martial Engolo
Status: Full Time
Hourly Rate: 22.27
Time Worked: 42.5
Press any key to close this window . . .

If you want to declare variables of the same type, you can use their common data type, followed by names separated by commas, and ending with a semicolon. Here is an example:

int width, height, depth;

You can initialize each variable with its own value. You don't have to initialize all variables, only those whose values you want to specify. This can be done as follows:

int width = 228, height, depth = 39;

Other than that, you can use each variable as we have done so far. Here are examples:

using static System.Console;

string firstName = "Martial", lastName = "Engolo";
string status = "Full Time";
double hourlySalary = 22.27, timeWorked = 42.50;

WriteLine("Employee Details");
WriteLine("============================");
Write("Employee Name: ");
Write(firstName);
Write(" ");
WriteLine(lastName);
Write("Status: ");
WriteLine(status);
Write("Hourly Rate: ");
WriteLine(hourlySalary);
Write("Time Worked: ");
WriteLine(timeWorked);

Practical LearningPractical Learning: Declaring Many Variables

  1. Change the document as follows:
    using static System.Console;
    
    string customerName      = "Geneviève Harrens",
           homePhone         = "(410) 386-2747";
    int    numberOfShirts    = 1,
           numberOfPants     = 1,
           numberOfDresses   = 1;
    double priceOneShirt     = 1.35,
           priceAPairOfPants = 2.25,
           priceOneDress     = 3.50;
    int    orderMonth        = 6,
           orderDay          = 22,
           orderYear         = 2020;
    
    WriteLine("-/-Georgetown Cleaning Services -/-");
    WriteLine("===================================");
    
    Write("Customer:   ");
    WriteLine(customerName);
    Write("Home Phone: ");
    WriteLine(homePhone);
    Write("Order Date: ");
    Write(orderMonth);
    Write('/');
    Write(orderDay);
    Write('/');
    WriteLine(orderYear);
    WriteLine("-----------------------------------");
    WriteLine("Item Type  Qty Sub-Total");
    WriteLine("------------------------");
    Write("Shirts      ");
    Write(numberOfShirts);
    Write("     ");
    WriteLine(priceOneShirt);
    Write("Pants       ");
    Write(numberOfPants);
    Write("     ");
    WriteLine(priceAPairOfPants);
    Write("Dresses     ");
    Write(numberOfDresses);
    Write("     ");
    WriteLine(priceOneDress);
    WriteLine("===================================");
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging. This would produce:
    -/-Georgetown Cleaning Services -/-
    ===================================
    Customer:   Geneviève Harrens
    Home Phone: (410) 386-2747
    Order Date: 6/22/2020
    -----------------------------------
    Item Type  Qty Sub-Total
    ------------------------
    Shirts      1     1.35
    Pants       1     2.25
    Dresses     1     3.50
    ===================================
    Press any key to close this window . . .
  3. Press Enter and return to your programming environment

Declaring a Variable When you Need it

As done above, you can first declare a variable, do some other things, then specify the value of the variable as long as you do this before using the variable. If your code is long, that approach can make your code difficult to read. The suggestion is to declare a variable only at the time you need it, namely at the time you are assigning a value to the variable for the first time. Here is an example:

using static System.Console;

string firstName = "Martial";
string lastName = "Engolo";

WriteLine("Employee Details");
WriteLine("============================");
WriteLine($"Employee Name: {firstName} {lastName}");

string status = "Full Time";

WriteLine($"Status: {status}");

double hourlySalary = 22.27;

WriteLine($"Hourly Rate: {hourlySalary}");

double timeWorked = 42.50;

WriteLine($"Time Worked: {timeWorked}");

Avoiding Unnecessary Variable Declarations

Consider the following code:

using static System.Console;

double distributionCharges = 124.48;
double environmentCharges = 12.45;

double totalCharges = distributionCharges + environmentCharges;

WriteLine($"Total Charges: {totalCharges}");

This would produce:

Total Charges: 136.93

Press any key to close this window . . .

As we saw in our introductions, the idea to declare a variable is to store a value in the computer memory. You do this because you anticipate that you will need to use that variable more than once. If you use a value only once, you may not need to declare a variable for it. You can use the value directly where it is needed. Here is an example:

using static System.Console;

double distributionCharges = 124.48;
double environmentCharges = 12.45;

WriteLine($"Total Charges: {distributionCharges + environmentCharges}");

This approach can reduce the number of lines of your code variables, from this:

using static System.Console;

double waterUseCharges;
double sewerUseCharges;

double usage = 21.86;

waterUseCharges = usage * 4.18;
sewerUseCharges = usage * 5.85;

WriteLine($"Water and Sewer Usage: {usage}");
WriteLine($"Water Use Charges:     {waterUseCharges:f}");
WriteLine($"Sewer Use Charges:     {sewerUseCharges:F}");

To this:

using static System.Console;

double usage = 21.86;
double waterUseCharges = usage * 4.18;
double sewerUseCharges = usage * 5.85;

WriteLine($"Water and Sewer Usage: {usage}");
WriteLine($"Water Use Charges:     {waterUseCharges:f}");
WriteLine($"Sewer Use Charges:     {sewerUseCharges:F}");

This would produce:

Water and Sewer Usage: 21.86
Water Use Charges:     91.37
Sewer Use Charges:     127.88

Press any key to close this window . . .

But if you do too much, it can make your code difficult (in fact it can get worse, especially if you include of the things we haven't studied such as conditional statements, collections, etc).

Inferring the Value of a Variable

To make it easy for you to declare variables, the C# language provides a keywork named var. You can use it to declare a variable of any type. If you use this keyword, you must immmediately initialize the variable. This means that, unlike the actual data types we have used so far, you must initialize a var variable when you declare it. This allows the compiler to figure out the type of value of the variable. The formula to follow is:

var variable-name = value;

Here is an example:


var fullName = "Martial Engolo";
double hourlySalary;

WriteLine("Employee Details");
WriteLine("=======================");

hourlySalary = 22.27;

Write("Employee Name: ");
WriteLine(fullName);
Write("Houly Rate: ");
WriteLine(hourlySalary);

An Anonymous Type

We saw that, to use a class, you could first declare a variable for it and initialize it. Fortunately, you don't have to use a class to initialize an object. You can declare a variable that resembles an instance of a class and initialize it as you see fit. This is referred to as an anonymous type. To use it, declare the variable using the var keyword and use the new operator to allocate memory for it. Instead of using the name of a class, type an opening and a closing curly brackets after the new operator. In the curly brackets, state a name for each member as if it were the member of the class and initialize each member variable with the desired value. After the closing curly bracket, end the declaration with a semi-colon. Here is an example:

var BookInformation = new
{
    Title = "Calculus 6e Edition",
    Pages = 1074,
    Cover = "Hard Back"
};

After initializing the anonymous type, you can access each one of its members using the name of the variable followed by the period operator, and followed by the member variable. Here is an example:

using static System.Console;

var BookInformation = new
{
    Title = "Calculus 6e Edition",
    Pages = 1074,
    Cover = "Hard Back"
};

WriteLine("=//= BookInformation =//=");
Write("Title:         ");
WriteLine(BookInformation.Title);
Write("Nbr of Pages:  ");
WriteLine(BookInformation.Pages);
Write("Type of Cover: ");
WriteLine(BookInformation.Cover);

This would produce:

=//= BookInformation =//=
Title:         Calculus 6e Edition
Nbr of Pages:  1074
Type of Cover: Hard Back
Press any key to close this window . . .

Remember that spreading the declaration on many lines only makes it easy to read. Otherwise, you can as well include everything on the same line.

using static System.Console;

var book = new { Title = "Calculus 6e Edition", Pages = 1074 };

WriteLine("=//= BookInformation =//=");
Write("Title:         ");
WriteLine(BookInformation.title);
Write("Nbr of Pages:  ");
WriteLine(BookInformation.pages);

Values Types, Primitive Types

Introduction

We saw that, when you declare a variable, the compiler reserves an area in the computer memory for that variable. That area is primarily filled with garbage. If you assign a value to the variable, the compiler fills the reserved memory with that value. Sometimes, you want to change the value of a variable. We saw that this is referred to as updating the variable. What happens depends on the type of variable.

The Mutability of a Type

Creatures of our natural life change a lot. Some changes are visible and instantaneous, such as a changing larga or a blossoming flower. An object is said to be mutable when it can change its state or appearance.

A variable is said to be mutable if its value can change. This means that, if a data type allows mutability, when you change the value of that variable, the compiler goes in the memory area that was reserved for the variable and replaces the previous value with the new one. The types that allow this mechanism are referred to as value types, also referred to as primitive types. Examples of value types or primitive types are int and double that we have used so far.

The Immutability of a Type

Some data types don't allow you to change the value of their variable. In this case, when you assign a new value to their variable, instead of replacing the value in the computer memory reserved for that variable, the compiler instead uses a different memory area and puts the new value in that memory area. The immutability is the opposite to mutability. A data type that doesn't allow you to replace its current value with a new one is said to be immutable. An example of immutable data type is the string type.

Constants

Suppose you intend to use a number such as 39.37 over and over again. Here is an example:

using static System.Console;

double meter, inch;
		
meter = 12.52;
inch = meter * 39.37;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

Here is an example of running the program:

12.52 = 492.9124in

A constant is a value that never changes such as 244, "ASEC Mimosa", or 39.37. These are constant values you can use in your program any time. You can also declare a variable and make it a constant; that is, use it so that its value is always the same.

To let you create a constant, C# provides the const keyword. Type it to the left of the data type of a variable. When declaring a constant, you must initialize it with an appropriate value. Here is an example:

const double ConversionFactor = 39.37;

Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant would be used. Here is an example of a constant variable used various times:

using static System.Console;

const double conversionFactor = 39.37;
double meter, inch;

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

This would produce:

12.52 = 492.9124in

12.52 = 492.9124in

12.52 = 492.9124in

To initialize a constant variable, the value on the right side of "=" must be a constant or a value that the compiler can determine as constant. Instead of using a known constant, you can also assign it another variable that has already been declared as constant.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Thursday 23 November 2023 Next