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. 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 Create a New Project, make sure ASP.NET Core Web App is selected (if not, click it).
    Click Next
  3. Change the Project Name to StellarWaterPoint02
  4. Click Next
  5. Make sure the Framework Frame combo box is displaying .NET 7.0 (Standard Term Support). Uncheck Configure For HTTPS
  6. Click Create
  7. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  8. In the Add New Scaffolded Item dialog box, in the middle list, make sure Razor Page - Empty is selected. Click Add
  9. In the Add New Item dialog box, change the file Name to CustomerInvoice
  10. 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 bodies or sections of code. Curly brackets are also used to create variable scope.

Parentheses: ( and )

Parentheses are used to isolate a group of items that must be considered as belonging to one entity. 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:

@{
    string firstName, lastName, fullName;
}

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:

@{
    double salary;

    // Using the assignment operator
    salary = 12.55;
}

Once a variable has been declared and assigned a value, you can display its value.  Here is an example:

@{
    double salary;

    // Using the assignment operator
    salary = 12.55;
}

<p>Employee's Hourly Salary: @salary</p>

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 the assignment operator
    double salary = 12.55;
}

<p>Employee's Hourly Salary: @salary</p>

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:

@{
    // Initializing various variables when declaring them with the same data type
    double value1 = 224.58, value2 = 1548.26;
}
		
<p>Value 1 = @value1</p>
<p>Value 2 = @value2</p>

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. If you want to display double-quotes on a webpage, you can use &".

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:

@{
    int numer = 802;
    int result = +802;
}

<p>Number: @numer</p>
<p>Incremented: @result</p>

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:

@{
    int numer = 802;
    int increment = +802;
    int decrement = -802;
}

<p>First Number: @numer</p>
<p>Incremented: @increment</p>
<p>Decremented: @decrement</p>

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:

@{
    int addition = 244 + 835;
}

<p>244 + 835 = @addition</p>

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

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:

@{
    string firstName = "Alexander";
    string lastName  = "Kallack";
    string fullName  = firstName + " " + lastName;
}

<p>Full Name: @fullName</p>

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:

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

    string result = salary + rate;
}

<p>@result</p>

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:

@{
    int value = 12;
}

<p>Techniques of incrementing a value</p>
<p>Value = @value</p>

@{
    value = value + 1;
}

<p>Value = @value</p>

This would produce:

Techniques of incrementing a value

Value = 12

Value = 13

There is 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:

@{
    int value = 12;
}

<p>Techniques of incrementing a value</p>
<p>Value = @value</p>

@{
    value++;
}

<p>Value = @value</p>

++ 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. Here are examples:

@{
    int value = 12;
}

<p>Techniques of incrementing a value</p>

@{
    value++;
}

<p>Value = @value</p>

@{
    value++;
}

<p>Value = @value</p>

@{
    value++;
}

<p>Value = @value</p>

This would produce:

Techniques of incrementing a value
Value = 13
Value = 14
Value = 15

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:

@{
    int value = 12;
}

<p>Techniques of incrementing a value</p>

<p>Value = @value</p>

@{
    ++value;
}

<p>Value = @value</p>

<p>Value = @value</p>

This would produce:

Techniques of incrementing a value
Value = 12
Value = 13
Value = 13

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.

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:

@{
    double value = 12.75;
    double newValue;
}

<p>Techniques of incrementing and decrementing a value</p>
<p>Value = @value</p>

@{
    newValue = value + 2.42;
}

<p>Value = @newValue

This would produce:

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

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:

@{
    double value = 12.75;
}

<p>Techniques of incrementing and decrementing a value</p>
<p>Value = @value</p>

@{
    value += 2.42;
}

<p>Value = @value</p>

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

@{
    double value = 12.75;
    int nbr = 3;
}

<p>Techniques of incrementing and decrementing a value</p>

@{
    string result = $"Value = {value}";
}

<p>Number: @result</p>

@{
    value += nbr;
    result = $"Value = {value}";
}

<p>Value = @value</p>

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";
}

<p>Name = @name</p>

@{
    name = name + "my";
}

<p>Name = @name</p>

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";
}

<p>Name = @name</p>

@{
    name += "my";
}

<p>Name = @name</p>

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:

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

<p>@value1 * @value2 = @result</p>

This would produce:

224.58 * 1548.26 = 347708.2308

Compound Multiplication

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

@{
    double value = 12.75;
}

<p>Value = @value</p>

@{
    value = value * 2.42;
}

<p>Value = @value</p>

This would produce:

Value = 12.75
Value = 30.855

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:

@{
    double value = 12.75;
}

<p>Value = @value</p>

@{
    value *= 2.42;
}

<p>Value = @value</p>

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:

@{
    double value1 = 224.58, value2 = 1548.26;
    double result = value1 - value2;
}

<p>@value1 - @value2 = @result</p>

This would produce:

224.58 - 1548.26 = -1323.68

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:

@{
    int number1 = 128 + 42 + 5;
    int number2 = 5 + 42 + 128;
}

<p> =+= Addition =+=</p>
<p>128 + 42 +   5 = @number1</p>
<p>5 + 42 + 128 = @number2</p>

@{
    // This tests whether the subtraction is associative
    number1 = 128 - 42 - 5;
    number2 = 5 - 42 - 128;
}

<p> =-= Subtraction =-=</p>
<p>128 - 42 - 5 = @number1</p>
<p>  5 - 42 - 128 = @number2</p>

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.

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:

@{
    int value = 12;
}

<p>Techniques of decrementing a value</p>
<p>Value = @value</p>

@{
    value = value - 1;
}

<p>Value = @value</p>

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11

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:

@{
    int value = 12;
}

<p>Techniques of decrementing a value</p>
<p>Value = @value</p>

@{
    value--;
}

<p>Value = @value</p>

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:

@{
    int value = 12;
}

<p>Techniques of decrementing a value</p>
<p>Value = @value</p>

@{
    int result = --value;
}

<p>Value = @result</p>

<p>Value = @value</p>

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11
Value = 11

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:

@{
    int value = 12;
}

<p>Techniques of decrementing a value</p>
<p>Value = @value</p>

@{
    int result = value--;
}

<p>Value = @result</p>

<p>Value = @value</p>

This would produce:

Techniques of decrementing a value
Value = 12
Value = 12
Value = 11

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:

@{
    double value = 12.75;
}

<p>Techniques of incrementing and decrementing a value</p>
<p>Value = @value</p>

@{
    value -= 2.42;
}

<p>Value =@value</p>

This would produce:

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

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:

@{
    double value1 = 224.58, value2 = 1548.26;
    double result = value1 / value2;
}

<p>@value1 / @value2 = @result</p>

This would produce:

224.58 / 1548.26 = 0.145053156446592

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 Operators

  1. To perform operations, change the document as follows:
    @page
    @model StellarWaterPoint02.Pages.CustomerInvoiceModel
    @{
        string accountType = "Residential Household";
    
        int counterReadingStart = 92863;
        int counterReadingEnd = 224926;
        int gallons = counterReadingEnd - counterReadingStart;
    
        double HCFTotal = gallons / 748;
    
        double first25Therms = 25.00 * 0.53713;
        double next15Therms = 15.00 * 0.36149;
        double above40Therms =  (HCFTotal - 40.00) * 0.1624;
    
        double waterUsageCharges = first25Therms + next15Therms + above40Therms;
        double sewerCharges = (waterUsageCharges * 0.2528) / 2.00;
     
        double environmentCharges = waterUsageCharges * 0.0000582;
        double serviceCharges = waterUsageCharges * 0.01368;
    
        double totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges;
    
        double localTaxes = totalCharges * 0.038379;
        double stateTaxes = totalCharges * 0.013816;
    
        double amountDue = totalCharges + localTaxes + stateTaxes;
    
        string strFirst25Therms = $"{first25Therms:F}";
        string strNext15Therms = $"{next15Therms:F}";
        string strAbove40Therms = $"{above40Therms:F}";
        string strHCFTotal = $"{HCFTotal:F}";
        string strWaterUsageCharges = $"{waterUsageCharges:F}";
        string strSewerCharges = $"{sewerCharges:F}";
        string strServiceCharges = $"{serviceCharges:F}";
        string strEnvironmentCharges = $"{environmentCharges:F}";
        string strTotalCharges = $"{totalCharges:F}";
        string strStateTaxes = $"{stateTaxes:F}";
        string strLocalTaxes = $"{localTaxes:F}";
        string strAmountDue  = $"{(totalCharges + localTaxes + stateTaxes):F}";
    }
    
    <h2 style="text-align: center">Stellar Water Point - Customer Invoice</h2>
        
    <hr />
    
    <h3 style="text-align: center">Meter Reading</h3>
        
    <hr />
    
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 175px">Type of Account:</td>
            <td>@accountType</td>
        </tr>
    </table>
    
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 175px">Counter Reading Start:</td>
            <td style="width: 175px">@counterReadingStart</td>
            <td>Counter Reading End:</td>
            <td>@counterReadingEnd</td>
        </tr>
        <tr>
            <td>Gallons:</td>
            <td>@gallons</td>
            <td>HCF Total:</td>
            <td>@strHCFTotal</td>
        </tr>
    </table>
        
    <hr />
    
    <h3 style="text-align: center">Therms Evaluation</h3>
        
    <hr />
    
    <table style="width: 100%">
        <tr>
            <td>Water Usage Charges:</td>
            <td>@strWaterUsageCharges</td>
            <td>Sewer Charges:</td>
            <td>@strSewerCharges</td>
        </tr>
        <tr>
            <td></td>
            <td>First 25 Therms:  @strFirst25Therms</td>
            <td>Next 15 Therms:  @strNext15Therms</td>
            <td>Above 40 Therms:  @strAbove40Therms</td>
        </tr>
    </table>
        
    <hr />
    
    <h3 style="text-align: center">Bill Values</h3>
        
    <hr />
    
    <table style="width: 700px" align="center">
        <tr>
            <td>Environment Charges:</td>
            <td>@strEnvironmentCharges</td>
            <td>Service Charges:</td>
            <td>@strServiceCharges</td>
        </tr>
    </table>
    <hr />
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 100px"></td>
            <td style="width: 100px"></td>
            <td>Total Charges:</td>
            <td>@strTotalCharges</td>
        </tr>
    </table>
    <hr />
    <table style="width: 700px" align="center">
        <tr>
            <td></td>
            <td>Local Taxes:</td>
            <td>@strLocalTaxes</td>
            <td></td>
            <td>State Taxes:</td>
            <td>@strStateTaxes</td>
        </tr>
    </table>
        
    <hr />
    
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 250px"></td>
            <td style="width: 100px"></td>
            <td>Amount Due:</td>
            <td>@strAmountDue</td>
        </tr>
    </table>
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Variables

  3. In the address bar of the browser, click the right side of the address, type /CustomerInvoice and press Enter

    Introduction to Variables

  4. 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:

@{
    double value = 12.75;
}

<p>Value = @value</p>

@{
    value = value / 2.42;
}

<p>Value = @value</p>

This would produce:

Value = 12.75
Value = 5.26859504132231

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

@{
    double value = 12.75;
}

<p>Value = @value</p>

@{
    value /= 2.42;
}

<p>Value = @value</p>

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:

@{
    int players = 18;
    int remainder = players % 11;
}

<p>Out of @players players, @remainder players will have to wait when the game starts.</p>

This would produce:

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

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:

@{
    int players = 18;
    int result = players % 11;
}

<p>Out of @players players, @result players will have to wait when the game starts.</p>

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:

@{
    int Players = 18;
}

<p>Out of @players players, 

@{
    players %= 11;
}

@players players will have to wait when the game starts.</p>

Options on Declaring and Managing Variables

Constants

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

@{
    double meter, inch;

    meter = 12.52;
    inch = meter * 39.37;
}

<p>@meter = @inch in.</p>

Here is an example of running the program:

12.52 = 492.9124 in.

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:

@{
    const double conversionFactor = 39.37;
    double meter, inch;

    meter = 12.52;
    inch = meter * ConversionFactor;
}

<p>@meter = @inch in.</p>

@{
    meter = 12.52;
    inch = meter * ConversionFactor;
}

<p>@meter = @inch in.</p>

@{
    meter = 12.52;
    inch = meter * ConversionFactor;
}

<p>@meter = @inch in.</p>

This would produce:

12.52 = 492.9124 in.

12.52 = 492.9124 in.

12.52 = 492.9124 in.

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.

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:

@{
    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. When accessing the variable, put it in parentheses with its @ symbol. Since you are accessing the variable, precede it with the @ sign. Here are examples:

@{
    int    @(@double) = 3648;
    double @(@static) = 248.59;
    string @(@class)  = "Nuclear Energy";
}

<pre>Values
-------------------------
Distance: @@double miles
Net Pay:  @@static
Industry: @@class</pre>

This would produce:

Values
-------------------------
Distance: 3648 miles
Net Pay:  248.59
Industry: Nuclear Energy

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:

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

<pre>Values
-------------------------
Description: @(@description)
Quantity:  @(@quantity)
Size: @(@size)
Unit Price: @unitPrice</pre>

This would produce:

Values
-------------------------
Description: Short Sleeve Shirt
Quantity:  26
Size: Medium
Unit Price: 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.

Updating a Variable

When declaring a variable, you don't have to initialize it. This means that you can declare a variable, perform some 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:

@{
    data-type variable-name;

    // Optionally do other things here...

    variable-name = desired-value;
}

Here are examples:

@{
    string fullName;
    double hourlySalary;
}

@{
    hourlySalary = 22.27;
    fullName = "Martial Engolo";
}

<pre>Employee Details
=======================
Employee Name: @fullName
Houly Rate: @hourlySalary</pre>

This would produce:

Employee Details
=======================
Employee Name: Martial Engolo
Houly Rate: 22.27

Still, you can initialize a variable, perform some 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:

@{
    string fullName = "Martial Engolo";
    double hourlySalary = 22.27;
}

<pre>Employee Details
=======================
Employee Name: @fullName
Hourly Rate: @hourlySalary

@{
    hourlySalary = 35.08;
    fullName = "Annette Sandt";
}

----------------------
Employee Name: @fullName
Hourly Rate: @hourlySalary</pre>

This would produce:

Employee Details
=======================
Employee Name: Martial Engolo
Hourly Rate: 22.27
----------------------
Employee Name: Annette Sandt
Hourly Rate: 35.08

Practical LearningPractical Learning: Updating Variables

  1. Change the document as follows:
    @page
    @model StellarWaterPoint02.Pages.CustomerInvoiceModel
    @{
        string accountType = "";
    
        int counterReadingStart = 0;
        int counterReadingEnd = 0;
        int gallons = 0;
    
        double HCFTotal = 0.00;
    
        double first25Therms = 0.00;
        double next15Therms = 0.00;
        double above40Therms =  0.00;
    
        double waterUsageCharges = 0.00;
        double sewerCharges = 0.00;
     
        double environmentCharges = 0.00;
        double serviceCharges = 0.00;
    
        double totalCharges = 0.00;
    
        double localTaxes = 0.00;
        double stateTaxes = 0.00;
    
        double amountDue = 0.00;
        
        accountType = "Social/Non-Profit Organization";
    
        counterReadingStart = 92863;
        counterReadingEnd = 224926;
        gallons = counterReadingEnd - counterReadingStart;
    
        HCFTotal = gallons / 748;
    
        first25Therms = 25.00 * 0.53713;
        next15Therms = 15.00 * 0.36149;
        above40Therms =  (HCFTotal - 40.00) * 0.1624;
    
        waterUsageCharges = first25Therms + next15Therms + above40Therms;
        sewerCharges = (waterUsageCharges * 0.41693) / 2.00;
     
        environmentCharges = waterUsageCharges * 0.0000582;
        serviceCharges = waterUsageCharges * 0.03369;
    
        totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges;
    
        localTaxes = totalCharges * 0.028379;
        stateTaxes = totalCharges * 0.008816;
    
        amountDue = totalCharges + localTaxes + stateTaxes;
    
        string strFirst25Therms = $"{first25Therms:F}";
        string strNext15Therms = $"{next15Therms:F}";
        string strAbove40Therms = $"{above40Therms:F}";
        string strHCFTotal = $"{HCFTotal:F}";
        string strWaterUsageCharges = $"{waterUsageCharges:F}";
        string strSewerCharges = $"{sewerCharges:F}";
        string strServiceCharges = $"{serviceCharges:F}";
        string strEnvironmentCharges = $"{environmentCharges:F}";
        string strTotalCharges = $"{totalCharges:F}";
        string strStateTaxes = $"{stateTaxes:F}";
        string strLocalTaxes = $"{localTaxes:F}";
        string strAmountDue  = $"{(totalCharges + localTaxes + stateTaxes):F}";
    }
    
    . . .
  2. To execute the application and make sure ther is no error, on the main meni, click Debug -> Start Without Debugging.
    If the browser presents a Resend button, click that button. Otherwise, refresh the browser:

    Introduction to Variables

  3. Return to your programming environment

Declaring Many Variables With a Common Type

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

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

<pre>Employee Details
============================
Employee Name: @firstName @lastName
Status: @status
Hourly Rate: @hourlySalary
Time Worked: @timeWorked</pre>

This would produce:

Employee Details
============================
Employee Name: Martial Engolo
Status: Full Time
Hourly Rate: 22.27
Time Worked: 42.5

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:

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

<pre>Employee Details
============================
Employee Name: @firstName @lastName
Status: @status
Hourly Rate: @hourlySalary
Time Worked: @timeWorked</pre>

Practical LearningPractical Learning: Declaring Many Variables

  1. Change the document as follows:
    @page
    @model StellarWaterPoint02.Pages.CustomerInvoiceModel
    @{
        string accountType = "";
    
        int counterReadingStart = 0, counterReadingEnd = 0, gallons = 0;
        double HCFTotal = 0.00;
        double first25Therms = 0.00, next15Therms = 0.00, above40Therms =  0.00;
        double waterUsageCharges = 0.00, sewerCharges = 0.00;
        double environmentCharges = 0.00, serviceCharges = 0.00;
        double totalCharges = 0.00, localTaxes = 0.00, stateTaxes = 0.00, amountDue = 0.00;
        
        accountType = "Water Intensive Business (Laundromat, etc";
    
        counterReadingStart = 92863;
        counterReadingEnd = 224926;
        gallons = counterReadingEnd - counterReadingStart;
    
        HCFTotal = gallons / 748;
    
        first25Therms = 25.00 * 0.53713;
        next15Therms = 15.00 * 0.36149;
        above40Therms =  (HCFTotal - 40.00) * 0.1624;
    
        waterUsageCharges = first25Therms + next15Therms + above40Therms;
        sewerCharges = (waterUsageCharges * 0.86393) / 2.00;
     
        environmentCharges = waterUsageCharges * 0.0014869;
        serviceCharges = waterUsageCharges * 0.096853;
    
        totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges;
    
        localTaxes = totalCharges * 0.417593;
        stateTaxes = totalCharges * 0.296402;
    
        amountDue = totalCharges + localTaxes + stateTaxes;
    
        string strFirst25Therms = $"{first25Therms:F}";
        string strNext15Therms = $"{next15Therms:F}";
        string strAbove40Therms = $"{above40Therms:F}";
        string strHCFTotal = $"{HCFTotal:F}";
        string strWaterUsageCharges = $"{waterUsageCharges:F}";
        string strSewerCharges = $"{sewerCharges:F}";
        string strServiceCharges = $"{serviceCharges:F}";
        string strEnvironmentCharges = $"{environmentCharges:F}";
        string strTotalCharges = $"{totalCharges:F}";
        string strStateTaxes = $"{stateTaxes:F}";
        string strLocalTaxes = $"{localTaxes:F}";
        string strAmountDue  = $"{(totalCharges + localTaxes + stateTaxes):F}";
    }
    
    <h2 style="text-align: center">Stellar Water Point - Customer Invoice</h2>
        
    <hr />
    
    <h3 style="text-align: center">Meter Reading</h3>
        
    <hr />
    
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 175px">Type of Account:</td>
            <td>@accountType</td>
        </tr>
    </table>
    
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 175px">Counter Reading Start:</td>
            <td style="width: 175px">@counterReadingStart</td>
            <td>Counter Reading End:</td>
            <td>@counterReadingEnd</td>
        </tr>
        <tr>
            <td>Gallons:</td>
            <td>@gallons</td>
            <td>HCF Total:</td>
            <td>@strHCFTotal</td>
        </tr>
    </table>
        
    <hr />
    
    <h3 style="text-align: center">Therms Evaluation</h3>
        
    <hr />
    
    <table style="width: 100%">
        <tr>
            <td>Water Usage Charges:</td>
            <td>@strWaterUsageCharges</td>
            <td>Sewer Charges:</td>
            <td>@strSewerCharges</td>
        </tr>
        <tr>
            <td></td>
            <td>First 25 Therms:  @strFirst25Therms</td>
            <td>Next 15 Therms:  @strNext15Therms</td>
            <td>Above 40 Therms:  @strAbove40Therms</td>
        </tr>
    </table>
        
    <hr />
    
    <h3 style="text-align: center">Bill Values</h3>
        
    <hr />
    
    <table style="width: 700px" align="center">
        <tr>
            <td>Environment Charges:</td>
            <td>@strEnvironmentCharges</td>
            <td>Service Charges:</td>
            <td>@strServiceCharges</td>
        </tr>
    </table>
    <hr />
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 100px"></td>
            <td style="width: 100px"></td>
            <td>Total Charges:</td>
            <td>@strTotalCharges</td>
        </tr>
    </table>
    <hr />
    <table style="width: 700px" align="center">
        <tr>
            <td></td>
            <td>Local Taxes:</td>
            <td>@strLocalTaxes</td>
            <td></td>
            <td>State Taxes:</td>
            <td>@strStateTaxes</td>
        </tr>
    </table>
        
    <hr />
    
    <table style="width: 700px" align="center">
        <tr>
            <td style="width: 250px"></td>
            <td style="width: 100px"></td>
            <td>Amount Due:</td>
            <td>@strAmountDue</td>
        </tr>
    </table>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging.
    If the browser presents a Resend button, click that button. Otherwise, refresh the browser:

    Introduction to Variables

  3. 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:

@{
    string firstName = "Martial";
    string lastName = "Engolo";
}

<pre>Employee Details
============================
Employee Name: @firstName @lastName

@{
    string status = "Full Time";
}

Status: @status

@{
    double hourlySalary = 22.27;
}

Hourly Rate: @hourlySalary

@{
    double timeWorked = 42.50;
    string result = $"Time Worked: {timeWorked}";
}

Time Worked @result </pre>

Avoiding Unnecessary Variable Declarations

Consider the following code:

@{
    double distributionCharges = 124.48;
    double environmentCharges = 12.45;

    double totalCharges = distributionCharges + environmentCharges;
}

<p>Total Charges: @totalCharges</p>

This would produce:

Total Charges: 136.93

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:

@{
    double distributionCharges = 124.48;
    double environmentCharges = 12.45;
    double result = distributionCharges + environmentCharges;
}

<p>Total Charges: @result</p>

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

@{
    double waterUseCharges;
    double sewerUseCharges;

    double usage = 21.86;

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

    string strUsage           = $"Water and Sewer Usage: {usage}";
    string strWaterUseCharges = $"Water Use Charges: {waterUseCharges:f}";
    string strSewerUseCharges = $"Sewer Use Charges: {sewerUseCharges:F}";
}

<p>Water and Sewer Usage: @strUsage</p>
<p>@strWaterUseCharges</p>
<p>@strSewerUseCharges</p>

To this:

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

    string strUsage = $"Water and Sewer Usage: {usage}";
    string strWaterUseCharges = $"Water Use Charges:     {waterUseCharges:f}";
    string strSewerUseCharges = $"Sewer Use Charges:     {sewerUseCharges:F}";
}

<p>Water and Sewer Usage: @strUsage</p>
<p>Water Use Charges:     @strWaterUseCharges</p>
<p>Sewer Use Charges:     @strSewerUseCharges</p>

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 to read (in fact it can get worse, especially if you include some of the things we haven't studied yet).

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;
}

<p>Employee Details</p>

@{
    hourlySalary = 22.27;
}

<p>Employee Name: @fullName</p>
<p>Houly Rate: @hourlySalary</p>

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 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.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2023, FunctionX Sunday 19 December 2021 Next