Functions Fundamentals

Introduction to Functions

A function is a section of code that performs an action that other sections of a program can refer to. You create a function by writing code. The fundamental formula to create a function is:

options function-name(...)
{
}

The creation of a function starts with one or more options. We will study those options little by little as we move in our lessons.

In the previous lessons, we saw that, to declare a variable in the source code of a Web page, first create a section that starts with @{ and end the section with }. In that section, you can also create a function. Based on this, the formula to create a function is:

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

As an option, to create a function in the source code of a Web 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 in 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(...)
    {
    }
}

Practical LearningPractical Learning: Introducing Functions

  1. Start Microsoft Visual Studio. Create a new ASP.NET Core Web App that supports the .NET 7.0 (Standard Term Support) named PieceWork1. Uncheck the Configure For HTTPS check box
  2. In the Solution Explorer, right-click Pages -> Add -> Razor Page
  3. In the Add New Scaffolded Item dialog box, make sure Razor Page - Empty is selected.
    Click Add
  4. Change the file Name to ProductDelivery
  5. Click Add
  6. Change the document as follows:
    @page
    @model PieceWork1.Pages.ProductDeliveryModel
    @{
        int    miles = 0;
        double pieceworkRate = 0.00;
    
        string strPieceWorkRate = $"{pieceworkRate}";
    }
    
    <pre>- Piece Work Delivery -
    ====================================
    Miles Driven:   @miles
    Piecework Rate: @strPieceWorkRate</pre>
  7. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging
  8. On the browser, click the right side of the address text, type /ProductDelivery and press Enter:
    - Piece Work Delivery -
    ====================================
    Miles Driven:   0
    Piecework Rate: 0
  9. Return to your programming environment

The Name of a Function

A function must have a name. That name must follow some rules:

The Parentheses of a Function

The name of a function is followed by parentheses. At a minimum, the parentheses can be empty. Most of the time, you will write the parentheses on the same line as the name of the function. Otherwise, you can write each parenthesis on its own line. Here is an example:

options CarryMe
(
)

Or like this:

options CarryMe(
           )

Or like this:

options CarryMe
     (
     )

The Body of a Function

The body of a function follows the parentheses. After the parentheses, add the brackets: { and }. Here are examples:

@functions
{
    options Send(){}

    options Publish(){
    }

    options Salute(
    ){}

    options Continue(
    ){
    }

    options Announce
    (){}

    options CarryMe
    (
    )
    {
    }
}

The section between the curly brackets is the body of the function. In that body, you can write the code that describes what the function is supposed to do.

The Scope and Lifetime of a Variable

Introduction

The scope of a variable is the extent to which it is available to other members of a project. To manage this, a variable is said to have local or global scope.

Local Variables

A variable is said to be local if it is declared in the body of a function. Here is an example:

@functions
{
    options Create()
    {
	string middleName;
    }
}

When a variable is declared as local, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.

A Global Variable

A variable is said to be global if it is declared outside any function. Here is an example:

@{
    string strDateOfBirth;

    options Initialize()
    {

    }

    options Present()
    {
    }
}

A variable that has been declared globally can be accessed by any C# code of the same document.

Returning from a Function

A Void Function

The creation of a function starts with some options. As the most basic option you can specify for a function, start it with a keyword named void. Here is an example:

@functions
{
    void Create()
    {
    }
}

Returning for No Reason

As seen in our introduction, a function has a body, which is delimited by curly brackets. Still, to indicate the end of execution of a function, you can type a keyword named return followed by a semicolon. Here are examples:

void Communicate()
{
    return;
}
    
void NeedToDiscuss()
{
    return;
}
    
void TakeCare()
{
    return;
}

In this case, the return; statement doesn't serve any true purpose, but it can be made useful in other circumstances.

Returning a Value From a Function

We saw that the creation of a function starts with some options. As one of those options, you can indicate that the function you are creating will produce a value. In this case, we say that the function returns a value. To indicate that the function you are creating must produce a value, as the option of that function, write the desired data type on the left side of the name of the function you are creating. Here is an example:

@{
    double Calculate()
    {
    }
}

Then, before the closing curly bracket of the function, type the return keyword, followed by what to return, followed by a semicolon.

Returning a Constant Value

The Primary way to return from a function is with a value. The value must the same type as, or be compatible with, the return type of the function. Here are examples:

int ProduceANumber()
{
    return 2000;
}

int GetTriple()
{
    return 3000;
}

Returning a Variable

You can also return a variable. To do this, outside the function in the body of the function, first declare a variable. In the body of the function, if necessary, perform any operation you want. You can then assign a value or expression to the variable. Then, on the last line of the function, type return followed by the name of the variable. Here are examples:

@{
    int nbr;

    int GetNumber()
    {
        return nbr;
    }

    int GetTriple()
    {
        int result = Number * 3;

        return result;
    }
}

Returning an Expression

An expression is a combination of values, variables, or values and variable. You can create a function that returns such a combination, as long as the expression is compatible with the return type of the function. Here are examples:

@{
    string firstName = "Jeremie";
    string lastName = "Gibson";

    int Triple()
    {
        int number = 284_740;

        return number * 3;
    }

    string ShowFullName()
    {
          return firstName + " " + lastName;
    }
}

A Simple Returning Function with no Body

Consider the following functions:

@{
    int nbr = 3_250;

    int DoubleTheNumber()
    {
        return nbr * 2;
    }

    int GetTriple()
    {
        return nbr * 3;
    }
}

If a function is small enough and it returns a value, remove the body of the curly brackets of the body of the function. After the parentheses of the function, type => followed by the returning expression and a semicolon. Here are examples:

@{
    int nbr = 3_250;

    int DoubleTheNumber() => nbr * 2;

    int GetTriple() => nbr * 3;
}

Calling a Function

Introduction

After creating a function, you can use it. Using a function is referred to as calling it. To call a simple function, type its name, followed by parentheses. You 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.

A Void Function

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 earlier, you can call a function in an @functions{} or an @{} section. You can also call a function in the source code of your HTML file. 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>

Storing a Function Call in a Variable

If you have a function that produces a value and you use that value more than once, you can assign the function call to a variable and then use that variable as you see fit. Here are examples:

@{
    int ProduceANumber()
    {
        return 2000;
    }

    int GetTriple()
    {
        return 3000;
    }

    int value = 3250;
    
    double total = GetTriple();
}

<p>Number: @ProduceANumber()</p>
<p>Triple: @total</p>

This would produce:

Number: 2000
Triple: 3000
==============================================
Press any key to close this window . . .

You can also use this technique if the function returns a variable. Here are examples:

@{
    int nbr;

    int ProduceNumber()
    {
        return nbr;
    }

    int GetTriple()
    {
        int result = Number * 3;

        return result;
    }

    int value = 3250;

    nbr = value;
    double total = GetTriple();
}

<p>Number: @Number</p>
<p>Triple: @total</p>

This would produce:

Number: 3250
Triple: 9750
==============================================
Press any key to close this window . . .

Calling a Function Where it is Needed

Normally, when you call a function and assign the call to a variable, you are probably planning to use the returned value many times. If you are planning to use the returned value many times, you can call the function directly where its value is needed.

Returning a function Call

Imagine you have a function that returns a value. Imagine that you have to call that function in the body of another function to get the returned value of that function. Here are examples:

@{
    int nbr;

    int MultiplyBy4()
    {
        return nbr * 4;
    }

    int Calculate()
    {
        int u = 38;
        int w = nbr * 3;

        return u + w;
    }

    int GetNumber()
    {
        int x = 428;
        nbr = x;

        int a = MultiplyBy4();

        return a;
    }

    int Summarize()
    {
        int y = 3_258;
        nbr   = y * 8;

        int q = Calculate();

        return q;
    }

    nbr = 44;
}

<p>Number:  @GetNumber()</p>
<p>Summary: @Summarize()</p>

This would produce:

Number:  1712
Summary: 78230
==============================================
Press any key to close this window . . .

Notice that, in both cases, the property and the methods return a value produced by a function they are calling. In such a case, instead of storing the returned value of the function in a variable, you can call the function directly on the return line. Here are examples:

@functions
{
    int nbr;

    int MultiplyBy4()
    {
        return nbr * 4;
    }

    int Calculate()
    {
        int u = 38;
        int w = nbr * 3;

        return u + w;
    }

    int GetNumber()
    {
        int x = 428;
        nbr = x;

        return MultiplyBy4();
    }

    int Summarize()
    {
        int y = 3_258;
        nbr   = y * 8;

        return Calculate();
    }

    nbr = 44;
}

lt;p>Number:  @GetNumber()</p>
<p>Summary: @Summarize()</p>

Previous Copyright © 2001-2023, FunctionX Wednesday 25 November 2021 Next