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(...)
{
}

Practical LearningPractical Learning: Introducing Functions

  1. Start Microsoft Visual Studio and create a new Console App that supports the .NET 9.0 (Standard Term Support) named PieceWork1
  2. Change the document as follows:
    using static System.Console;
    
    int    miles = 0;
    double pieceworkRate = 0.00;
    
    WriteLine("====================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("====================================");
    WriteLine("Miles Driven:   {0}", miles);
    WriteLine("Piecework Rate: {0:n}", pieceworkRate);
    WriteLine("====================================");
  3. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging
    ============================================
     - Piece Work Delivery -
    ============================================
    Miles Driven:   0
    Piecework Rate: 0.00
    ============================================
    Press any key to close this window . . .
  4. Press T to close the window and return to your programming environment

A Void Function

The creation of a function starts with some options. As the simplest option you can apply, start a function with a keyword named void (that keyword is required for now).

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:

void CarryMe
(
)

Or like this:

void CarryMe(
           )

Or like this:

void CarryMe
     (
     )

The Body of a Function

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

void Send(){}

void Publish(){
}

void Salute(
){}

void Continue(
){
}

void Announce
(){}

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

Practical LearningPractical Learning: Creating Functions

Calling a Function

After creating a function, you can use it. Using a function is referred to as calling it. To call a simple function like the one we created above, type its name, followed by parentheses, and end it with a semicolon. This would be done as follows:

void Publish(){
}

Publish();

Practical LearningPractical Learning: Calling Functions

  1. Change the document as follows:
    using static System.Console;
    
    int    miles = 0;
    double pieceworkRate = 0.00;
    
    void GetMiles()
    {
        Write("Miles Driven:   ");
        miles = int.Parse(ReadLine());
    }
    
    void GetWorkRate()
    {
        Write("Piecework Rate: ");
        pieceworkRate = double.Parse(ReadLine());
    }
    
    WriteLine("==============================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("==============================================================");
    WriteLine("To evaluate the employee's pay, type the following information");
    GetMiles();
    GetWorkRate();
    WriteLine("==============================================================");
    WriteLine("Pay Summary");
    WriteLine("--------------------------------------------------------------");
    WriteLine("Miles Driven:   {0}", miles);
    WriteLine("Piecework Rate: {0:n}", pieceworkRate);
    WriteLine("==============================================================");
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. For the number of Miles, type 1417 and press Enter
  4. For the Piecework Rate, type .47 and press Enter
    ==============================================================
     - Piece Work Delivery -
    ==============================================================
    To evaluate the employee's pay, type the following information
    Miles Driven:   1417
    Piecework Rate: .47
    ==============================================================
    Pay Summary
    --------------------------------------------------------------
    Miles Driven:   1417
    Piecework Rate: 0.47
    ==============================================================
    
    Press any key to close this window . . .

Nesting a Function

Sometimes, you will find out that a function you had created is useful to only one other function. This means that, in this case, only a certain function A calls a certain function B and no other function calls that function B. If you have a section of code that only a certain function calls, you can create a function for that section in the body of the unique function that calls it.

A local function is a function that is created in the body of another function. A function created inside another function is also referred to as nested. The C# language provides various options to nest a function.

You primarily create a local function like any other, as long as you create it in the body of another function. After creating a nested function, call it by its name as we have done for the others.

Region Delimiters

Code Sections Delimiters

Microsoft Visual Studio provides various techniques to assist you with code writing and management. The characteristics include color-coded words, intuitive indentation, the IntelliSense, delimitation of sections of code, etc. Consider the following contents of the Code Editor based on what we have reviewed so far:

Code Editor - Regions - Collapsed

Notice that there are - buttons (dash buttons) on the left side of some lines of code. These allow you to collapse a section of code if you think you don't need to see it. To do this, you can click the - button (the dash button). If you click that - button, it changes into a + button (a plus button). Here is an example:

Code Editor - Regions - Expanded

The + button allows you to expand a hidden code section. This behavior of creating + and - buttons is part of the Code Editor of Microsoft Visual Studio. To create these sections, the Code Editor follows some rules. For example, it looks for the start and end of such an item as a function.

Regions

Besides, or instead of, the sections of code created by the Code Editor, if you want, you can create your own sections. To create a section:

When and where you start a region, the #region expression is required. On the right side of this expression, you can type anything you want on the line. To end the section, type #endregion, followed by anything you want. Consider the following example:

int someVariable;

#region This section is reserved for quadrilateral shapes
void ProcessRectangle()
{
}

void ShowSquare()
{
}
#endregion This is the end of the quadrilateral section

string message;

You don't have to type anything on the right side of #endregion. After creating the region, the Code Editor would display a - button (dash) to the left side of #region with a line from there to the left of #endregion:

Regions in the Code Editor

This then allows you to expand and collapse that section at will:

Regions in the Code Editor

We mentioned that you didn't have to type anything on the right side of #endregion and you could leave it empty. In our example, notice that there is a rectangle with gray lines around the string that follows #region. This rectangle doesn't cover the string that follows #endregion. This means that if you don't type anything on the right side of #endregion, that section on the right side of the #region line would not show.

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:

void 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 (directly) in the Code Editor; that is, outside any curly brackets or outside any function. Here is an example:

string strDateOfBirth;

void Initialize()
{

}

void Present()
{
}

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

A Function that Returns a Value

Introduction

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, type the return keyword 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. It can be made useful when associated with a conditional statement.

Returning From a Function

A function can be made to return a value. That is, if a function doesn't produce an explicit value, set its return type to void. If a function must produce a value, write the 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. Here are examples:

int ProduceANumber()
{
    return 2000;
}

int GetTriple()
{
    return 3000;
}

In this case, we say that the function is returning a constant.

Returning a Variable

You can also return a variable. To do this, in the body of the function, declare a variable. 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;
}

A Simple Returning Function with no Body

Consider the following functions:

using static System.Console;

int nbr = 3_250;

int DoubleTheNumber()
{
    return nbr * 2;
}

int GetTriple()
{
    return nbr * 3;
}

double total = GetTriple();

WriteLine($"Number: {nbr}");
WriteLine($"Double: {Doubler}");
WriteLine($"Triple: {total}");
WriteLine("==============================================");

This would produce:

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

If a function is small and it returns a value, you can simplify its code. To do this, 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:

using static System.Console;

int nbr = 3_250;

int DoubleTheNumber() => nbr * 2;

int GetTriple() => nbr * 3;

double total = GetTriple();

WriteLine($"Number: {nbr}");
WriteLine($"Double: {DoubleTheNumber}");
WriteLine($"Triple: {total}");
WriteLine("==============================================");

Topics on Calling a Function that Returns Something

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 is an example:

using static System.Console;

int ProduceANumber()
{
    return 2000;
}

int GetTriple()
{
    return 3000;
}

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

WriteLine($"Number: {ProduceANumber()}");
WriteLine($"Triple: {total}");
WriteLine("==============================================");

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:

using static System.Console;

int nbr;

int ProduceNumber()
{
    return nbr;
}

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

    return result;
}

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

WriteLine($"Number: {Number}");
WriteLine($"Triple: {total}");
WriteLine("==============================================");

This would produce:

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

Returning an Expression

We already know that, in a function, you can declare one or more variables, perform some operations on the values, ant then return a value that represents an operation. Such an operation may produce an expression, and you may want to return such an expression. In some cases, you can perform the operations, store the result in a variable, then then return that variable. Consider the following example:

using static System.Console;

string GetFullName()
{
    WriteLine("Enter the employee name.");
    Write("First Name: ");
    string fName = ReadLine();
    Write("First Name: ");
    string mName = ReadLine();
    Write("First Name: ");
    string lName = ReadLine();

    // Creating an expression to return and storing that expression in a variable
    string complete = fName + " " + mName + " " + lName;

    // Returning a variable
    return complete;
}

string fullName = GetFullName();

WriteLine("=======================================");
WriteLine("Employee Name: {0}", fullName);
WriteLine("=======================================");

Here is an example of running the program:

Enter the employee name.
First Name: Michael
First Name: Justin
First Name: Carlock
=======================================
Employee Name: Michael Justin Carlock
=======================================

In some cases, you don't need to first store the expression in a variable and return that variable. You can just return the expression. Here is an example:

using static System.Console;

string GetFullName()
{
    WriteLine("Enter the employee name.");
    Write("First Name: ");
    string fName = ReadLine();
    Write("First Name: ");
    string mName = ReadLine();
    Write("First Name: ");
    string lName = ReadLine();

    return fName + " " + mName + " " + lName;
}

string fullName = GetFullName();

WriteLine("=======================================");
WriteLine("Employee Name: {0}", fullName);
WriteLine("=======================================");

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 not planning to use the returned value many times, you can call the function directly where its value is needed. Here are examples:

using static System.Console;

double Doubler()
{
    double number = 973.64;

    return number + number;
}

double Tripler()
{
    double a = 244.47;
    double threeTimes = a + a + a;

    return threeTimes;
}

Console.WriteLine("==============================================================");
Console.WriteLine("Numbers");
Console.WriteLine("==============================================================");
Console.WriteLine("Two times of 973.64 is {0}", Doubler());
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine("The triple of 244.47 is {0}", Tripler());
Console.WriteLine("==============================================================");

This would produce:

==============================================================
Numbers
==============================================================
Two times of 973.64 is 1947.28
--------------------------------------------------------------
The triple of 244.47 is 733.41
==============================================================
Press any key to close this window . . .

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 is an example:

using static System.Console;

double number = 973.64;

double Doubler()
{
    return number + number;
}

double TwoTimer()
{
    Console.WriteLine("==============================");
    Console.WriteLine("Number");

    double result = Doubler();

    double a = 244.47;
    double threeTimes = a + a + a;

    Console.WriteLine("------------------------------");
    Console.WriteLine("The triple of 244.47 is {0}", threeTimes);
    
    return result;
}

Console.WriteLine("973.64 + 973.64 = {0}", TwoTimer());
Console.WriteLine("==============================");

This would produce:

==============================
Number
------------------------------
The triple of 244.47 is 733.41
973.64 + 973.64 = 1947.28
==============================
Press any key to close this window . . .

Notice that you have a function that returns a value produced by calling another function. 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:

using static System.Console;

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;

WriteLine($"Number:  {Number}");
WriteLine($"Summary: {Summarize()}");
WriteLine("==============================================");

Ignoring the Returned Value of a Function

When a function is configured to return a value, when calling that function, we have seen that you can assign its call to a variable and use that variable as you see fit. Here is an example:

using static System.Console;

int zipCode = 20680;
int numberOfDays = 30;
int counterStart = 10089;
int counterEnd = 11126;

Console.WriteLine("Electric Bill Evaluation");
Console.WriteLine("======================================================");

string strDisplayed = DisplayBill();

Console.WriteLine(strDisplayed);

string DisplayBill()
{
    const double custChargeRate = 0.49315;
    const double nrgChargeRate  = 0.16580;
    const double envChargeRate  = 0.00043;

    int electricUse = counterEnd - counterStart;

    double custCharge = numberOfDays * custChargeRate;
    double energyCharge = electricUse * nrgChargeRate;
    double envControlCharge = electricUse * envChargeRate;

    double serviceTotal;

    Console.WriteLine("Electric Bill Summary:");
    Console.WriteLine("======================================================");
    Console.WriteLine("Counter Reading Start:        {0, 8}", counterStart);
    Console.WriteLine("Counter Reading End:          {0, 8}", counterEnd);
    Console.WriteLine("Total Electric Use:           {0, 8}", electricUse);
    Console.WriteLine("Number of Days:               {0, 8}", numberOfDays);
    Console.WriteLine("------------------------------------------------------");
    Console.WriteLine("Energy Charge Credit");
    Console.WriteLine("------------------------------------------------------");
    Console.WriteLine("Customer Chargee:             {0, 8:f}", custCharge);
    Console.WriteLine("Energy Charge:                {0, 8:f}", energyCharge);
    Console.WriteLine("Environmental Control Charge: {0, 8:f}", envControlCharge);
    Console.WriteLine("------------------------------------------------------");

    serviceTotal = custCharge + energyCharge + envControlCharge - 3.15;
    Console.WriteLine("Low Income Assistance Fee:    {0, 8:f}", 3.15);
    serviceTotal = custCharge + energyCharge + envControlCharge;
    Console.WriteLine("Electric Servive Total:       {0, 8:f}", serviceTotal);
    Console.WriteLine("======================================================");

    return "The customer bill has been displayed";
}

This would produce:

Energy Charge Credit
------------------------------------------------------
Customer Chargee:               14.794
Energy Charge:                 171.935
Environmental Control Charge:    0.446
------------------------------------------------------
Low Income Assistance Fee:       3.150
Electric Servive Total:        187.175
======================================================
The customer bill has been displayed

Press any key to close this window . . .

Although a function may return a value, sometimes when calling such a function, you may not be interested in the returned value of that function. You have many options. As done above, you can declare a variable and assign the function call to it, but this is a waiste of resources because the compiler will have allocated memory space for a variable you are not planning to use. As another option, in the placeholder of the variable and its data type, simply type an underscore. Here is an example:

using static System.Console;

int zipCode = 20680;
int numberOfDays = 30;
int counterStart = 10089;
int counterEnd = 11126;

Console.WriteLine("Electric Bill Evaluation");
Console.WriteLine("======================================================");

_ = DisplayBill();

string DisplayBill()
{
    . . .

    return "The customer bill has been displayed";
}

The last option is to simply call the function without assigning it to a variable or to an underscore placeholder. Here is an example:

using static System.Console;

. . .

WriteLine("Electric Bill Evaluation");
WriteLine("======================================================");

DisplayBill();

string DisplayBill()
{
    . . .
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2025, FunctionX Sunday 17 February 2025, 22:06 Next