Introduction to Functions and Methods

Introduction to Functions

A function is a section of code that performs an action to which other sections of a program can refer. In a Razor Page, first create a section that starts with @{ and end the section with }. In that section, you can create a function. Based on this, the formula to create a function is:

@{
    options function-name(...)
    {
    }
}

As an option, to create a function in a Razor Page, start a section with @functions, an opening curly bracket {, and end it with a closing curly bracket }. This can be done as follows:

@functions
{
    options function-name(...)
    {
    }
}

If you want, you can write each curly bracket on its own line. Inside the curly brackets, create your function(s). In the @{} or the @functions{} section, you can create as many functions are you want. This would be done as follows:

@{
    options function-name-1(...)
    {
    }

    options function-name-2(...)
    {
    }

    options function-name-x(...)
    {
    }
}

In the same document, you can create @{} and @functions{} sections. This can be done as follows:

@{
    options function-name-1(...)
    {
    }

    options function-name-2(...)
    {
    }
}

Anything can go here

@function{
    options function-name-4(...)
    {
    }

    options function-name-5(...)
    {
    }
}

@{
    options function-name-y(...)
    {
    }
}

The body of a function follows the parentheses. You can write the parentheses on the same line or on different lines. In the same way, you can write the curly brackets on the same or different lines. These would be done as follows:

@functions
{
    options Send(){}

    options Publish(){
    }

    options Salute(
    ){}

    options Continue(
    ){
    }

    options Announce
    (){}

    options CarryMe
    (
    )
    {
    }
}

When creating a function, follow the same rules and techniques available in C#.

Local and Global Variables

You can declare a variable in the body of a function. This is referred to as a local variable. You can declare a variable outside any function. This is referred to as a global variable.

Returning from a Function

When creating a function, you must indicate its return type. If it doesn't return an actual value, specify its return value as void. Here is an example:

@functions
{
    void Create()
    {
    }
}

To indicate the end of execution of a function, you can type the return keyword in its body. Here is an example:

@{
    void Communicate()
    {
        return;
    }
}

Otherwise, to indicate the type of value that the function must return, write that type before the name of the function. In the function, before the closing curly bracket, type the return keyword, followed by what to return, followed by a semicolon. Here are examples:

@{
    int ProduceANumber()
    {
        return 2000;
    }
}

Otherwise, the function return rules are the same as done in C#.

Calling a Function

Introduction

To use a function, you can call it. You can call a function in the same @functions{} or @{} section where it is defined or you can call a function in a separate @{} section. If you call a function in an @functions{} or an @{} section, you must end the call with a semicolon. If you call a function in an HTML tag (outside an @functions{} or @{} section), don't use a semicolon, or the semi-colon is not part of the function call. This means that you can add a semicolon as part of some text you want to display in the webpage.

Void Functions and Razor Pages

If you have a function created with the void keyword (whether you created the function yourself or you are using someone else's function), you can call that function only inside an @functions{} or an @{} section, not in an HTML tag. Here is an example:

@functions{
    void Present()
    {
    }
}

@{
    Present();
}

Calling a Function that Returns a Value

As mentioned above, you can call a function in an @functions{} or an @{} section. You can also call a function in the source code of your HTML document. In this case, create an HTML tag and call the function in it. Here is an example:

@functions
{
    int See(){
	   return 3_972_746;
    }
}

<p>@See()</p>

The rules and suggestions for calling a function are the same as done in C#.

Introduction to Methods

A method is a function that is created in the body of a class. That is, a method is a member function of a class. Everything we have mentioned so far for functions is the same for a method, except that a method is created in the body of a class.

A Method in a Page Model

A Page Model is primarily a regular class. In that class, you can create one or more methods. For example, you can create a simple void method. When you create a Razor Page as we know already, Microsoft Visual Studio automatically creates a default void method named OnGet in it. Here is an example:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Operations.Pages
{
    public class AdditionModel : PageModel
    {
        public void OnGet()
        {

        }
    }
}

When you open the webpage associated with a Page model, its OnGet() method is automatically called. As a result, if you want to do something on the webpage as soon as it opens, you can perform such an operation in the OnGet() method of the Page Model. For example, if you had declared a variable in the body of the Page Model class, you can initialize that variable in the OnGet() method. Here is an example:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Exercises.Pages
{
    public class ExerciseModel : PageModel
    {
        public int MarketValue;

        public void OnGet()
        {
            MarketValue = 493_855;
        }
    }
}

You can then access the variable in the Razor Page using the @Model object as we saw already.

In the same way, you too can create one or more methods in the Page Model class. If you are planning to access a method in the Razor Page, you must mark it with the public or internal access level. You can create a method that returns a regular value (a method that returns int, double, string, etc). Here is an example:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Operations.Pages
{
    public class AdditionModel : PageModel
    {
        public void OnGet()
        {
        }

        public int Triple()
        {
            const int number = 384_825;

            return number * 3;
        }
    }
}

You can call such a method in the Razor Page to display the returned value using the @Model. Here is an example:

@page
@model Operations.Pages.AdditionModel
@{
}

<p>Number: @Model.Triple()</p>

Introduction to Parameters and Arguments

Introduction to the Parameters of a Function/Method

You can create a function or method that uses one or more parameters as values that would be given to the function or method when doing its job. A parameter is provided in the parentheses of the function or method. In the body of the function or method, you can use the parameter. Here is an example:

@functions{
    string ProtectFromBadWeather(string typeOfRoof)
    {
        return $"Roof Type: {typeOfRoof}";
    }
}

In the body of the function or method, you can ignore or use the parameter. The data type of a parameter can be any primitive type you want or object.

A Function or Method with Many Parameters

A function or method can use many parameters. The parameters can be the same type or different types. Here is an example:

@{
    void ShowTimeWorked(string startTime, string endTime)
    {

    }
}

When calling a function or method that uses a parameter, you must provide a value for the parameter. The action of providing a value in the parentheses of the function or method is referred to as passing an argument. Here is an example:

@page
@model Valuable.Pages.FoundationsModel
@{
}

@functions{
    string propertyType = "Single Family";
    int    bedrooms = 5;
    double marketValue = 482995;

    string ProtectFromBadWeather(string typeOfRoof)
    {
        return $"Roof Type: {typeOfRoof}";
    }
}

<pre>=//= Altair Realtors =//=
Properties Inventory
Property Type: @propertyType
@ProtectFromBadWeather("Asphalt Shingles")
Bedrooms: @bedrooms
Market Value: @marketValue</pre>

This would produce:

=//= Altair Realtors =//=
Properties Inventory
Property Type: Single Family
Roof Type: Asphalt Shingles
Bedrooms: 5
Market Value: 482995

If the value is stored in a variable, you can pass the name of the variable to the function or method. Here is an example:

@page
@model Valuable.Pages.FoundationsModel
@{
}

@functions{
    string propertyType = "Single Family";
    int    bedrooms = 5;
    double marketValue = 482995;
    string roofMaterial = "Affiche Shingles";

    string ProtectFromBadWeather(string typeOfRoof)
    {
        return $"Roof Type: {typeOfRoof}";
    }
}

<pre>=//= Altair Realtors =//=
Properties Inventory
Property Type: @propertyType
@ProtectFromBadWeather(roofMaterial)
Bedrooms: @bedrooms
Market Value: @marketValue</pre>

Accessing a Parameter by Name

When calling a function or method that takes (an) argument()s, you can refer to each argument by the name of its parameter, followed by a colon, and followed by the appropriate value.

A Parameter With an Optional Value

If you have a function or method whose argument is usually given the same value, you can give a default value to that parameter. When calling the function, you can pass a value for the argument or you can omit passing the argument. Here is an example:

@page
@model Valuable.Pages.FoundationsModel
@{
}

@{
    double originalPrice;

    double CalculatePriceAfterDiscount(double discountRate = 20)
    {
        return originalPrice - (originalPrice * discountRate / 100);
    }

    double discountRate = 20.00; // 20%
    originalPrice   = 198.75;

    double priceAfterDiscount = CalculatePriceAfterDiscount();
    string strPrice = $"{priceAfterDiscount:F}";
}

<pre>Fun Department Store
===================================
Orignial Price:  @originalPrice
Discount Rate:   @discountRate%
-----------------------------------
Marked Price:    @strPrice</pre>

The rules for optional parameters are the same as done in C#.

A Parameter by Reference

You can create a function or method that takes one or more arguments and you must must provide a valid value when calling such a function or method. If you are using a parameter only for the value it is holding and you will not change the value of the parameter, such a parameter is said to be passed "in", which is done with the in keyword. Here is an example:

@page
@model Valuable.Pages.FoundationsModel
@{
}

@{
    double Subtract(in double a, in double b)
    {
        return a - b;
    }

    double CalculateDiscount(in double price, in double rate)
    {
        return price * rate / 100.00;
    }

    double cost = 169.95;
    int    dRate = 25;
    double discount = CalculateDiscount(cost, dRate);

    double markedValue = Subtract(cost, discount);
    string strPrice = $"{markedValue:F}";
}

<pre>Fun Department Store
===================================
Orignial Price:  @cost
Discount Rate:   @dRate %
-----------------------------------
Discount Amount: @discount
Marked Price:    @strPrice</pre>

Otherwise, you can pass the parameter by reference using the out or the ref keyword. The techniques of using the in, the out, and the ref keywords are the same as in C#.

Functions and Methods Conditional Returns

You can make the function or method produce a result that depends on some condition(s). To start, you can interrupt processing in the body of a function or method before the closing curly bracket with the return keyword. Here is an example:

@page
@model Valuable.Pages.FunctionalModel
@{
    string strOne = "";
    string strTwo = "";

    void SetTicketAmount()
    {
        strOne = "Computer";

        return;

        strTwo = "Science";
    }
}

@{
    SetTicketAmount();
}

<p>@strOne @strTwo</p>

Conditionally Returning a Variable

In such a function or method, you can create a condition statement, such as one created with if. Here is an example:

@functions{
    int SetTicketAmount(bool aggressive)
    {
        int fee = 45;

        if (aggressive == true)
            fee = 100;

        return fee;
    }
}

Of course, if you are using an if(something == true) condition, you can omit the == true section. Here is an example:

@functions{
    int SetTicketAmount(bool aggressive)
    {
        int fee = 45;

        if (aggressive)
            fee = 100;

        return fee;
    }
}

And of course, you can use any of the available Boolean operators. Here is an example:

@functions{
    int SpecifyDiscountRate(int days)
    {
        int rate = 15;

        if (days > 30)
            rate = 50;

        return rate;
    }
}

You can use any other appropriate Boolean operators such as is. Here is an example:

@functions{
    int SpecifyDiscountRate(int days)
    {
        int rate = 15;

        if(days is > 30)
            rate = 50;

        return rate;
    }
}

You can use an if...else conditional statement that checks a condition in a function or method, stores the result in a variable, and then return that result. Here is an example:

@functions{
    int SpecifyDiscountRate(int days)
    {
        int rate;
      
        if (days is <= 30)
            rate = 15;
        else
            rate = 50;
      
        return rate;
    }
}

You can also use an if...else if or an if...else if...else conditional statement to check a condition. Here is an example:

@functions{
    int SpecifyDiscountRate(int days)
    {
        int rate;

        if (days is > 70)
            rate = 70;
        else if(days is > 50)
            rate = 50;
        else if(days is > 30)
            rate = 35;
        else // if(days is > 15)
            rate = 15;
        
        return rate;
    }
}

Introduction to the Fields of a Class

Overview

You can declare a variable in the body of a class; that is, outside any method. Such a variable is called a field. Here are two fields in a class:

@{
    class House
    {
        int brightness;

        string security;
    }
}

By default, a field created by declaring a variable has private visibility, which is equivalent to creating it with the private keyword. If you want to access the field outside the class, mark it with the public keyword. Here are examples:

@functions{
    class House
    {
        // A public field
        public string BuildingPermit;
        // A public field
        public double MarketValue;
    }
}

If you want to create a field that only objects of the same project can access, mark it with the internal keyword.

After creating a field, to access it from its class, you can first declare a variable of the class.

A Field from a Page Model

One of the jobs you will want to perform regularly is to get values from a Page Model class to the Razor Page. To do this, you can declare a public variable in the body of a Page Model and make sure you initialize that variable, which you can do in the OnGet() method. Then, in the Razor Page, use the an object named Model that can be accessed with @Model, a period, and the name of the variable.

A field of a class can be made null. When creating the field, add a question mark to its data type. Here is an example:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Valuable.Pages
{
    public class ExerciseModel : PageModel
    {
        private int? length;

        public void OnGet()
        {
        }
    }
}

As seen with other fields, you can use a null one. If you are planning to access a field in a razor page, you must make that field public or internal.

As always, before using a field, you must initialize it. Once again, you have various options. You can initialize it with null. To provide an actual value to the field, you can use a constructor or a method of the class to assign a value to the field. Here is an example:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Valuable.Pages
{
    public class ExerciseModel : PageModel
    {
        public int? length;

        public void OnGet()
        {
            length = 29380;
        }
    }
}

A Field of a Class Type

You can declare a variable of a class type in the body of another class. If both classes are created in the same document, you can just use the name of the class to declare the variable. Here is an example:

@functions{
    class Processor
    {
        public string make;
        public string model;
        public int wattage;
        public double speed; 
    }

    class Computer
    {
        public string category;
        public string wirelessType;
        public Processor calculator;
    }
}

After declaring a variable of a class type, before using that variable, you must initialize it. This is also the case for a field of a class type. You have many options. You can initialize the field where it is created. Here is an example:

@functions{
    class House
    {
    }

    class State
    {
        House residence = new House();
    }
}

Alternatively, you can initialize the field in a method of the class. Here is an example:

@functions{
    class House
    {
    }

    class State
    {
        House residence;
        
        void Prepare()
        {
            residence = new House();
        }
    }
}

After creating the field whose type is a class, you can access the members of that type. To access a member of the type outside the class, after declaring a variable of the class, type the name of the variable, a period, the name of the field, a period, and the desired member. Here is an example:

@page
@model Valuable.Pages.ExerciseModel
@{
    Computer device = new Computer();

    device.category = "Desktop";

    device.calculator.make  = "AMD";
    device.calculator.model = "Ryzen";
}

@functions
{
    class Processor
    {
        public string make;
        public string model;
        public int    wattage;
        public double speed;
    }

    class Computer
    {
        public string    category;
        public string    wirelessType;
        public Processor calculator = new Processor();
    }
}

<pre>Computer Build-Up
--------------------------------
Category: @device.category
Make:     @device.calculator.make
Model:    @device.calculator.model</pre>

This would produce:

Computer Build-Up
--------------------------------
Category: Desktop
Make:     AMD
Model:    Ryzen

Introduction to the Constructors of a Class

Overview

A constructor is special method that provides the fundamental behavior and/or values of an object. A constructor uses the same name as the class, it doesn't return a value, and it should be marked with an access level. Here is an example:

@functions
{
    class House
    {
        public House()
        {
        }
    }
}

Using a Constructor

In the body of a constructor, you can access each field and assign the desired value to it. Here is an example:

class House
{
    public string type;
    public int beds;
    public double value;

    public House()
    {
        type = "Single-Family";
        beds = 5;
        value = 495_680;
    }
}

A Constructor with a Parameter

In your class, you can create a constructor that uses one or more parameters. Here are examples:

@{
    public class Square
    {
        public Square(double side)
        {

        }
    }
}

@functions{
    public class Exercise
    {
        public Exercise(string a, int b, int c)
        {
  	}
    }
}

In the body of the constructor, you can ignore or use the parameter(s). Here is an example:

@{
    public class Square
    {
        private double s;

        public Square(double side)
        {
            s = side;
        }
    }
}

Constructor Overloading

In your class, you can create as many constructors as you want. Those different constructors must follow the rules of method overloading. Here are examples:

@functions{
    public class Exercise
    {
        public Exercise(string a)
        {
        }

        public Exercise(string a, int b, int c)
        {
        }
    }
}

Creating an Object Using a Constructor

We already know that, when declaring a variable of a class type, you can initialize it with the new operator. You must then write the name of the class followed by parentheses. Here is an example we saw already:

@page
@model Valuable.Pages.FoundationsModel

@{
    House residence = new House();
}

A Constructor with No Body

If you are creating a small constructor that contains a single statement, you can replace the curly brackets with the => operator after the parentheses of the name of the constructor. This is followed by the necessary one-line statement. Here are examples:

@functions
{
    public class EquilateralTriangle
    {
        private double s;
        const double NumberOfSides = 3;

        public EquilateralTriangle() => s = 0;

        public EquilateralTriangle(double side) => s = side;

        public double CalculatePerimeter()
        {
            double dResult = 0;

            dResult = s * NumberOfSides;

            return dResult;
        }
    }
}

A Read-Only Field in a Class

When creating a field of a class, one of the decisions you must make is how the field would get its value(s). To create a field so that objects outside the class can only view its value but cannot change it while the value can be changed inside the class, create that field as read-only. To do this, when creating the field in the class, precede its data type with a keyword named readonly. Here is an example:

@functions{
    public class Circle
    {
        readonly double PI;
    }
}

To specify the value of a read-only field, use a constructor to initialize the field. Here is an example:

@functions{
    public class Circle
    {
        private double r;

        private readonly double PI;

        public Circle()
        {
       	    PI = 3.14;
        }
    }
}

A Constructor for a Page Model

As mentioned already, a page model is primarily a regular class like any other. When you create a razor page, Microsoft Visual Studio automatically creates the associated class and equips it with a default method named OnGet. Sometimes, you will want to perform various types of operations on that class, and for some of those operations, you may need a constructor. If you want a page model to use a constructor, you can easily add it.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2023, FunctionX Saturday 13 November 2021 Next