Fundamentals of Variables

Introduction to Values

A value is a piece of information (called data) you need to use in your program. One way to use a value is to display it to the user. To do this, you can create the value in the source code of a webpage, create an HTML tag, and include the desired value in that tag.

Practical LearningPractical Learning: Introducing Variables

  1. Start Microsoft Visual Studio
  2. To create a new application (if Microsoft Visual Studio was already opened, on the main menu, click File -> New -> Project...), on the Visual Studio 2022 dialog box, click Create a New Project
  3. In the Create a New Project dialog box, click ASP.NET Core Web App (it should be selected already) and click Next
  4. Change the Name of the project to StellarWaterPoint01
  5. Click Next
  6. In the Additional Information dialog box, make sure the Framework combo box is displaying .NET 7.0 (Standard Term Support). Make sure the Authentication Type combo box is displaying None. Remove the check mark on the Configure For HTTPS check box
  7. Click Create
  8. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  9. In the Add New Scaffolded Item dialog box, in the middle list, make sure Razor Page - Empty is selected. Click Add
  10. In the Add New Item dialog box, change the file Name to CustomerInvoice
  11. Click Add

Introduction to Variables

A variable is a value that is stored in the computer memory (the random access memory, also called RAM). Such a value can be retrieved from the computer memory and displayed to the user.

Declaring a Variable

Before using a variable in your application, you must let the compiler know. Letting the compiler know is referred to as declaring a variable.

To declare a variable, you must provide at least two pieces of information. Actually, you have various options. We will start with one of them. One option to declare a variable is to provide the type of value, also called a data type, followed by a name for the variable. The formula to follow is:

data-type variable-name;

If you are declaring the variable in the source code of a webpage, do it between @{ and }:

@{
    data-type variable-name;
}

Initializing a Variable

When declaring a variable, you can give it a primary value. This is referred to as initializing the variable. You can use the following formula:

@{
    data-type variable-name = value;
}

This would be done as follows:

@{
    data-type variable-name = desired-value;
}

The Name of a Variable

A variable must have a name. There are rules you must follow to specify the name of a variable. To start, you must avoid reserved words, also called keywords. These keywords are:

abstract and as async await base bool
break byte case catch char checked class
const continue decimal default delegate do double
dynamic enum else explicit extern event false
finally fixed float for foreach get global
goto if implicit in (foreach) in (generic) init int
interface internal is (Conditions) is (Nullity) lock long namespace
new (generic) new (inheritance) new (object) not null object operator
or out (generic) out (methods) override params private protected
public readonly record ref return sbyte sealed
set short sizeof stackalloc string struct switch
static this (class) this (indexer) throw true try typeof
unsafe using uint ulong ushort virtual value
var void when (Conditionals) when (Switch) where while with
yield

There are other names that are not considered C# keywords but should be avoided because they may cause a conflict in your code. They are referred to as contextual keywords. They are:

add ascending descending from group
into join let orderby partial (method)
partial (type) remove select where (generic) where (query)
     

There are some rules we will follow to name variables:

Besides these rules, you can also create your own rules but that follow the above restrictions. For example:

C# is case-sensitive. This means that the names Case, case, and CASE are completely different.

Introduction to Statements

A statements is a line of code that must indicate its end. The primary way a statement shows its end is with a semicolon. The primary statement in code is a variable declaration. Therefore, when you declare a variable, you must end it with a semicolon.

Displaying a Variable

Introduction

If you declare a variable in a @{} section of a webpage and that variable has a value, the value of that variable is not automatically displayed on the webpage. If you want to display the value of a declared variable, you have many options.

Displaying a Variable in Console Window

As mentioned in the previous lesson, you can write code that displays in the console window of your Web project. To display something in the console window, in a @{} section, write code as follows:

System.Console.WriteLine("");

At this time, we don't care what the words System, Console, and WriteLine mean. In later lessons, we will find out what every one of those words means. We will also know the purpose of the parentheses and double-quotes. In a previous section, we were introduced to the semicolon. For now, when you want to display a value in the console window of your Web project, write that value in the double-quotes of of System.Console.WriteLine("");. We will see various examples of doing that, and we will see various techniques of displaying values in the console window.

Displaying a Variable in a Web Page

To display a value on a webpage, outside the @{} section, create the HTML tag that is needed to display the variable. In the tag, type the name of the variable preceded by the @symbol. This can be done as follows:

@{
    data-type variable-name = desired-value;
}

<p>variable-name</p>

In the HTML tag, you can include anything else you want. The most important two rules are that:

A Primary Introduction to Strings

Introduction

A string one or a group of symbols, readable or not. The symbols can be letters (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z), digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) are non-readable characters (` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > "). To create a string, include its symbol, symbols, or combination inside double-quotes.

A String Variable

One way to use a string in a program is to store that string in the computer memory. To do that, you can declare a variable that holds a string as value. To declare a variable for a string, use a keywork named string. Here is an example:

@{
    string firstName;
}

To provide the value of the variable, specify its value in double-quotes and assign it to the variable. Here is an example:

@{
    string firstName = "James";
}

Displaying a String

Displaying a value consists of printing it to the computer screen. If you simply have a string to display, you can include that string in an HTML tag such as that of p. Here is an example:

<p>"Welcome to the World of C# Programming!"</p>

Introduction to Natural Numbers

Overview

A natural number is a value that contains only digits. For this type of a value, you use a data type named int. Use it to declare a variable that would hold a natural number. Here is an example:

@{
    int age;
}

The Value of an Integral Variable

To specify the variable of an int type, provide a value that contains only digits. Here is an example:

@{
    int age = 15;
}

Displaying an Integral Value

To display the numeric value of a variable, include that variable in an HTML tag and precede that variable with the @ symbol. Here is an example:

@{
    int age = 15;
}

<p>@age</p>

You can also use string interpolation to format the value of an integral variable before displaying it. To do this, as seen with strings, start the value with $ followed by double-quotes. In the double-quote, write {}. In those square brackets, include the name of the integral variable.

Creating a Large Integer

The value of an integer can be between -2147483648 and 2147484647 (or -2,147,483,648 and 2,147,484,647). If you need to use a large value, to make it easier to humanly read, you can separate the thousands by underscores. Here are examples:

@{
    int areaChina = 9_596_961;
    int areaCanada = 9_984_670;
    int areaBurkinaFaso = 275_200;
    int areaDjibouti = 23_200;
}

<p>Countries Areas"</p>
<p>---------------------</p>
<p>Djibouti: @areaDjibouti</p>
<p>Burkina Faso: @areaBurkinaFaso</p>
<p>China: @areaChina</p>
<p>Canada: @areaCanada</p>

Introduction to Floating-Point Numbers

Overview

A floating-point number is a number made of either only digits or two digit parts separated by a symbol referred to as a decimal separator. As one way to support floating-point numbers, you can use a data type named double. Use it to declare a variable for a number. To provide a value for the variable, you can use the same types of numbers we saw for integers. Here are examples:

@{
    double areaMaine = 35385;
    double areaAlaska = 1_723_337;
}

A Floating-Point Number with Precision

The primary difference between an integer and a floating-point number is that a decimal number can include a second part referred to as a precision. To specify the precision of a number, after the natural part, add the symbol used as the decimal separator. In US English, this is the period. Here is an example:

@{
    double hourlySalary = 25.85;
}

If the integral part is large, you can use it "as is" or you can separate its thousansds with underscores. Here are examples:

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

In the above examples, we used the underscore separator only on the integral part of the number. In reality, you can also use that separator in the precision side. Here are examples:

@{
    double number = 085.24_497;
    double value  = 947_596.75_038;
}

Displaying a Number with Fixed Precision

As is the case for integers and strings, to display the value of a decimal variable, you can included it in an HTML tag. You can also use string interpolation to display the value. Here are examples:

@{
    double number = 285.24_497;
    double value  = 947_596.75_038;
}

<p>@number</p>
<p>@value</p>

Practical LearningPractical Learning: Introducing Decimal Numbers

  1. Change the document as follows:
    @page
    @model StellarWaterPoint01.Pages.CustomerInvoiceModel
    @{
        string accountType = "Residential Household";
        int counterReadingStart = 92863;
        int counterReadingEnd = 224926;
        double amountDue = 55.73;
    }
    
    <h2 style="text-align: center">Stellar Water Point - Customer Invoice</h2>
        
    <hr />
    
    <h3 style="text-align: center">Meter Reading</h3>
        
    <hr />
    
    <table style="width: 600px" align="center">
        <tr>
            <td style="width: 175px">Type of Account:</td>
            <td style="width: 175px">@accountType</td>
            <td style="width: 175px">&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>Counter Reading Start:</td>
            <td>@counterReadingStart</td>
            <td>Counter Reading End:</td>
            <td>@counterReadingEnd</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>Amount to Pay:</td>
            <td>@amountDue</td>
            <td>&nbsp;</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
  5. Change the document as follows:
    @page
    @model StellarWaterPoint01.Pages.CustomerInvoiceModel
    @{
        string accountType = "Residential Household";
        
        int counterReadingStart = 92863;
        int counterReadingEnd = 224926;
        int gallons =  132063;
    
        double HCFTotal =  176.5548128342246;
    
        double first25Therms = 38.9325;
        double next15Therms = 18.396;
        double above40Therms =  131.42035187165777;
    
        double waterUsageCharges = 188.74885187165776;
        double sewerCharges = 47.56471067165776;
     
        double environmentCharges = 0.47187212967914444;
        double serviceCharges = 6.190962341390375;
    
        double totalCharges = 242.97639701438507;
    
        double localTaxes   = 1.277812871898651;
        double stateTaxes   = 0.549612610046539;
     	
        double amountDue = 244.80382249633027;
    }
    
    <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 style="width: 175px">@accountType</td>
            <td style="width: 175px">&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>Counter Reading Start:</td>
            <td>@counterReadingStart</td>
            <td>Counter Reading End:</td>
            <td>@counterReadingEnd</td>
        </tr>
        <tr>
            <td>Gallons:</td>
            <td>@gallons</td>
            <td>HCF Total:</td>
            <td>@HCFTotal</td>
        </tr>
    </table>
        
        <hr />
    
        <h3 style="text-align: center">Therms Evaluation</h3>
        
        <hr />
    
        <table style="width: 100%">
            <tr>
                <td>Water Usage Charges:</td>
                <td>@waterUsageCharges</td>
                <td>Sewer Charges:</td>
                <td>@sewerCharges</td>
            </tr>
            <tr>
                <td></td>
                <td>First 25 Therms (* 1.5573):  @first25Therms</td>
                <td>Next 15 Therms (* 1.2264):  @next15Therms</td>
                <td>Above 40 Therms (* 0.9624):  @above40Therms</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>@environmentCharges</td>
                <td>Service Charges:</td>
                <td>@serviceCharges</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>@totalCharges</td>
            </tr>
        </table>
        <hr />
        <table style="width: 700px" align="center">
            <tr>
                <td></td>
                <td>Local Taxes:</td>
                <td>@localTaxes</td>
                <td></td>
                <td>State Taxes:</td>
                <td>@stateTaxes</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>@amountDue</td>
            </tr>
        </table>
  6. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging.
    If the browser presents a dialog box with a Resend button, click that button. If not, refresh the browser:

    Introduction to Variables

  7. Return to your programming environment

String Interpolation

Introduction

String interpolation consists of inserting one string in another existing string to get a new string. To perform this operation, start the existing string with the $ sign. In the existing string, include a placeholder made of an opening curly bracket { and a closing curly bracket }. In the {} placeholder, include the desired variable. Here is an example:

@{
    string firstName = "Robert";

    string result = $"First Name: {firstName}";
}

<p>@result</p>

If you want to interpolate more strings, create as many {} sections as you want. In each {} placeholder, include the variable of your choice. Here is an example:

@{
    string firstName = "Robert";
    string lastName = "Ellis";

    string result = $"Customer: {firstName} {lastName}";
}

<p>@result</p>

String Interpolation with Floating-Point Numbers

Because floating-point numbers use a precision part, sometimes you want to control how the number displays. The string interpolation mechanism provides many options. To start, in the {} placeholder, after the name of the variable, type a colon (:). After the colon, if you want to display the number with two decimal places, type f or F, n. Here are examples:

@{
    double nbr = 4848075.5279;
    double val = 63828493.806;
    double number = 28835.24_497;
    double value  = 947_596.75_038;

    string result1 = $"Number: {nbr:f}";
    string result2 = $"Value: {val:f}";
    string result3 = $"Number: {number:F}";
    string result4 = $"Value: {value:F}";
}

<p>@result1</p>
<p>@result2</p>
<p>@result3</p>
<p>@result4</p>

Practical LearningPractical Learning: Introducing String Interpolation

  1. Change the document as follows:
    @page
    @model StellarWaterPoint01.Pages.CustomerInvoiceModel
    @{
        string accountType = "Residential Household";
        
        int counterReadingStart = 92863;
        int counterReadingEnd = 224926;
        int gallons =  132063;
    
        double HCFTotal =  176.5548128342246;
    
        double first25Therms = 38.9325;
        double next15Therms = 18.396;
        double above40Therms =  131.42035187165777;
    
        double waterUsageCharges = 188.74885187165776;
        double sewerCharges = 47.56471067165776;
     
        double environmentCharges = 0.47187212967914444;
        double serviceCharges = 6.190962341390375;
    
        double totalCharges = 242.97639701438507;
    
        double localTaxes   = 1.277812871898651;
        double stateTaxes   = 0.549612610046539;
     	
        double amountDue = 244.80382249633027;
    
        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 style="width: 175px">@accountType</td>
            <td style="width: 175px">&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>Counter Reading Start:</td>
            <td>@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 (* 1.5573):  @strFirst25Therms</td>
                <td>Next 15 Therms (* 1.2264):  @strNext15Therms</td>
                <td>Above 40 Therms (* 0.9624):  @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 dialog box with a Resend button, click that button. If not, refresh the browser:

    Introduction to Variables

  3. Return to your programming environment

Managing Variables

Introduction

Microsoft Visual Studio provides many tools you can use to manage code and manage your variables. The Code Editor of Microsoft Visual Studio provides many tools to assist you in managing your code.

If you are using Microsoft Visual Studio and if you want to find different occurrences of a known character, symbol, word, or group of words, first select that item. Then:

In the same way, if you have a variable that is used more than once in your code and you want to see all places where that variable is used, simply click the name (and wait a second) and all of its occurrences would be highlighted:

Name Selection

To get a list of all sections where the variable is used, if you are using Microsoft Visual Studio:

Find All References

This would produce a list of all sections where the variable is used and would display the list in the  Find Symbol Results window:

Find All References

To access a particular section where the variable is used, double-click its entry in the list.

Cutting, Copying, and Pasting Code

Normally, from your knowledge of using computers, you probably already know how to select, cut, and copy text. These two operations can be valuable to save code in Microsoft Visual Studio. This means that, if you have code you want to use in different sections, you can preserve it somewhere to access it whenever necessary.

To save code to use over and over again, first type the code in any text editor, whether in Notepad, Microsoft Word, or the Code Editor of Microsoft Visual Studio. You can use code from any document where text can be copied, including a web page. Select that code and copy it to the clipboard. To preserve it, in Microsoft Visual Studio, display the Toolbox (on the main menu, you can click View -> Toolbox). Right-click an empty area on the Toolbox and click Paste.

An alternative is to select the code, whether in the Code Editor or in a text editor. Then drag it and drop it on the Toolbox. In the same way, you can add different code items to the Toolbox. After pasting or adding the code to the Toolbox, it becomes available. To use that code, drag it from the Toolbox and drop it in the section of the Code Editor where you want to use it.

Renaming a Variable

As we will see throughout our lessons, there are many names you will use in your programs. After creating a name, in some cases you will have to change it. Microsoft Visual Studio makes it easy to find and change a name wherever it is used. To change the name of a variable, in the Code Editor, right-click any part of anywhere the name is used and click Rename:

Rename

A small window would then display with the current name dof the variable. You can then type the desired name and press Enter.

Accessing a Variable's Declaration

If you create a long document that has many lines of code, in a certain section you may encounter a variable but you want to find out where it was declared. If you are using Microsoft Visual Studio, to access the place where a variable was declared, ight-click the variable and click Go To Definition:

Go To Definition

In both cases, the caret would jump to where the variable was declared.

Accessing a Line of Code by its Index

If you are using the Code Editor of Microsoft Visual Studio, if you create a long document that has many lines of code, if you want to jump to a certain line of code:

This would display a dialog box. Enter the line number and click OK or press Enter.

Practical LearningPractical Learning: Ending the Lesson


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