Fundamentals of Variables

Introduction

A value is a piece of information (called data) you need to use in your program. One way to use a value is from a variable.

Practical LearningPractical Learning: Starting a Project

  1. Start Microsoft Visual Studio
  2. In the Visual Studio 2022 dialog box, under Get Started, click Create a New Project
  3. In the list of projects templates, click ASP.NET Core Web App

    New Project

  4. Click Next
  5. Change the Name to Variables
    Accept or change the Location
  6. Make sure the Framework combo box is displaying .NET 7.0 (Standard Term Support)
  7. Remove the check mark on Configure For HTTPS
  8. Click Create
  9. In the Solution Explorer, expand wwwroot and expand css
  10. Double-click site.css to open it
  11. At the end of the existing formats, add the following ones:
    html {
      font-size: 14px;
    }
    
    @media (min-width: 768px) {
      html {
        font-size: 16px;
      }
    }
    
    .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus {
      box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb;
    }
    
    html {
      position: relative;
      min-height: 100%;
    }
    
    body {
      margin-bottom: 60px;
    }
    
    .w100        { width:       100px;  }
    .w125        { width:       125px;  }
    .w150        { width:       150px;  }
    .ta-right    { text-align:  right;  }
    .ta-center   { text-align:  center; }
    .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  12. In the Solution Explorer, right-click Pages -> New -> Folder
  13. Type WaterMeters
  14. In the Solution Explorer, right-click WaterMeters -> Add -> Razor Page...
  15. In the middle list of the Add New Scaffolded Item dialog box, make sure Razor Page - Empty is selected and click Add
  16. In the middle list of the Add New Item dialog box, make sure Razor Page - Empty is selected.
    Change the file Name to Create

    Add New Item

  17. Click Add

Declaring a Variable (in a Razor Page)

Before using a variable in your application, you must declare it. You have many options. At a minimum, to declare a variable, start with a data type such as int, double, float, decimal, bool, string, etc. The data type is followed by a name and a semicolon. You can declare a variable in a Razor Page. To do this, create a section that starts with @{ and ends with }. Normally, when you create a Razor Page, such a section is automatically created and you can use it. If necessary, you can create additional @{} sections. Then, in an @{} section, you can declare a variable. Here is an example:

@{
    int age;
}

Initializing a Variable

When declaring a variable, you can assign a value to it. This is referred to as initializing the variable. Here is an example:

@{
    int age = 15;
}

A Constant Variable

If you are planning to use a variable whose value will never change, you can declare it as a constant. To do this, apply the const keyword to the variable and initialize it. Here is an example:

@{
    const int distance = 28_364;
}

Displaying a Variable

If you declare a variable in an @{} section of a Razor Page and that variable has a value, if you want to display the value of the variable, you have many options.

To display a value on a webpage, outside the @{} section, create the HTML tag that is needed to display the value of 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:

Here is an example:

@{
    int age = 15;
}

<p>@age</p>

In the same way, you can display values of variables.

Operations on Variables

After declaring variables, you can perform operations on them. All algebraic operations are available: the addition, the subtraction, the multiplication, the division, and the remainder. You can also use operators such as parentheses when necessary. Incrementing (pre and post), decrementing (pre and post), and compound operations are also available.

The Nullity of a Value

Introduction

A variable is said to be null when its value cannot be clearly determined. When declaring a variable, to indicate that either it can hold an actual value or it can be null, after its data type, add a question mark. Here is an example:

@{
    int? length;
}

In the same way, when declaring a variable in a class, such as in a Page Model, you can indicate that it can be null by writing a question mark after the data type of the variable. Here is an example:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Valuable.Pages
{
    public class ExerciseModel : PageModel
    {
        public void OnGet()
        {
            int? length;>
        }
    }
}

To support the nullity of values, the C# language provides the null keyword. Therefore, you can assign null when declaring a null variable. Here are examples:

@page
@model PracticalLearning.Pages.NullityModel
@{
    string status;
    string firstName, lastName;
    
    // A floating-point variable of null type
    double? hourlySalary = null;
    // Another null floating-point variable
    double? timeWorked = null;
    // An integral variable of null type
    int? category = null;

    status = "Full-Time";
    firstName = "Martial";
    lastName = "Engolo";
    category = 3;
    timeWorked = 42.50;
    hourlySalary = 22.27;
}

<pre>Employee Details
==============================
Variables with valid values
------------------------------
Employee Name: @firstName lastName
Status:        @status
Hourly Rate:   @hourlySalary
Time Worked:   @timeWorked
Pay Category:  @category
==============================</pre>

This would produce:

Employee Details
==============================
With null variables
------------------------------
Employee Name:
Status:
Hourly Rate:
Time Worked:
Pay Category:
==============================
Employee Details
==============================
Variables with valid values
------------------------------
Employee Name: Martial Engolo
Status:        Full-Time
Hourly Rate:   22.27
Time Worked:   42.5
Pay Category:  3
==============================

The Null Forgiving Operator

You already know that, before using a variable, you must initialize it. In some cases, the value of a variable may come by other means. The null-forgiving operator indicates to the compiler that you are aware that the variable or object may be holding a null value but you know what you are doing. The null-forgiving operator is !. To apply it, simply type it on the right side of the object or value. Here is an example:

@page
@model PracticalLearning.Pages.NullityModel
@{
    int number = 100!;
}

&lt;pre&gt;Number: @number&lt;/pre&gt;

Strings

Introduction

A string is a white space, one, or more characters. To support strings, the .NET Framework provides the String class represented in C# by the string data type. You can use either the String class or the string type to declare a string variable. Here is an example:

@{
    string name;
}

Converting a Value or an Object to a String

To allow you to convert any value or object to a string, the object data type (that is, its equivalent Object class) is equipped with the overriden ToString method you can use.

String Operations

The .NET Framework provides the String class represented in the C# language by the string type. That class provides many properties and methods that can help you perform string-related operations such as addition, concatenation, formatting, case conversion (lowercase and uppercase), comparisons, character or sub-string replacement, character or sub-string removal, trimming, copying, interpolation, etc. Here is an example for a string interpolation:

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

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

<p>@result</p>

In those operations, you can involve various types of values. When it comes to string interpolation, 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 (or n), or any of the allowed characters. 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>

The Nullity of a String

A string is referred to as null if it doesn't (yet) have a(ny) character(s)s. This is usually the case when the string has just been created, or a string variable has just been declared. When you have just declared a variable, to indicate that it is null, assign the null keyword to it. The variable must be declared using the string data type, the String class, or the dynamic keyword.

A Null, Empty, or White-Spaced String

To let you find out whether a string is null or contains a white space, the String class is equipped with the static IsNullOrWhiteSpace() method.

Value Conversion

The values that a user types or selects in the controls of a Web form are primarily, strings. If you want to perform operations on them, you first have to convert them to the right type(s). To convert a value to a natural number, call the Parse() method of its type. In the parentheses, type the value to be converted. Here is an example:

@{
    string value = "3528";

    int number = int.Parse(value);
}

<p>@number</p>

Normally, the value you will want to convert may come from a control on a Web form. In this case, the value you will convert would be gotten from HttpRequest.Form[""]. In this case, you would provide the identifier of the control in the double-quotes.

String Building

To let you perform some operations on building a string from other strings, the .NET Framework provides the StringBuilder class.

Encoding and Decoding Characters

To support various operations on encoding and decoding characters, the .NET Framework provides various classes such as Encoding, UTF8Encoding, etc.

Mutability and Immutability

The Mutability of a Type

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 an immutable data type is the string type.

Practical LearningPractical Learning: Introducing Variables

  1. Change the Create.cshtml document as follows:
    @page
    @model Variables.Pages.WaterMeters.CreateModel
    @{
        int    meterId     = 1;
        string meterNumber = "392-44-572";
        string make        = "Constance Technologies";
        string meterModel  = "TG-4822";
        string meterSize   = "5/8 Inches";
    }
    
    <h1 class="ta-center fw-bold common-font">Water Meter Setup</h1>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <div class="form-holder common-font">
            <div class="row g-3 align-items-center">
                <div class="col-md-4">
                    <label class="col-form-label">Meter Id:</label>
                </div>
                <div class="col-md-8">
                    <input class="form-control" value="@meterId" />
                </div>
            </div>
    
            <hr />
            <div class="row g-3 align-items-center">
                <div class="col-md-4">
                    <label class="col-form-label">Meter #:</label>
                </div>
                <div class="col-md-8">
                    <input class="form-control" value="@meterNumber" />
                </div>
            </div>
    
            <hr />
            <div class="row g-3 align-items-center">
                <div class="col-md-4">
                    <label class="col-form-label">Make:</label>
                </div>
                <div class="col-md-8">
                    <input class="form-control" value="@make" />
                </div>
            </div>
    
            <hr />
            <div class="row g-3 align-items-center">
                <div class="col-md-4">
                    <label class="col-form-label">Model:</label>
                </div>
                <div class="col-md-8">
                    <input class="form-control" value="@meterModel" />
                </div>
            </div>
    
            <hr />
            <div class="row g-3 align-items-center">
                <div class="col-md-4">
                    <label class="col-form-label">Meter Size:</label>
                </div>
                <div class="col-md-8">
                    <input class="form-control" value="@meterSize" />
                </div>
            </div>
        </div>
    }
  2. To execute, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging
  3. Click the right side of the string in the address bar of the browser
  4. Type /WaterMeters/Create and press Enter
  5. Close the Webpage and return to your programming environment

Previous Copyright © 2001-2023, FunctionX Thursday 16 December 2021 Next