Functions Fundamentals

Introduction

As seen in our first introduction to methods, a function is a section of code that performs an action. You create a function by writing code. The fundamental formula to follow when creating a function is:

options function-name(...)
{
}

As you may know already, code in C# must be written inside an object layout, such as a class (or a structure). In C#, console and Windows Forms applications don't allow functions (created outside a class (or structures)), but other types of C# applications, such as web applications, allow functions. In our series of lessons here, a function is a section of code that behaves like it is created and used outside a class. In other words, we use functions here as indipendent entities, that is independent from a class.

Practical LearningPractical Learning: Introducing Functions

  1. Start Microsoft Visual Studio. In the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already opened, on the main menu, click File -> New -> Project...)
  2. In the Create a New Project dialog box, in the list of projects templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the name to SalaryEvaluation1
  5. Click Create
  6. Design the form as follows:

    Functions Fundamentals

    Control (Name) Text
    Label   Hourly Salary:
    TextBox txtHourlySalary 0.00
    Button btnCalculate Calculate
    Label   _______________________
    Label   Daily Salary:
    TextBox txtDailySalary  
    Label   Weekly Salary:
    TextBox txtWeeklySalary  
    Label   Biweekly Salary:
    TextBox txtBiweeklySalary  
    Label   Monthly Salary:
    TextBox txtMonthlySalary  
    Label   Yearly Salary:
    TextBox txtYearlySalary  
  7. Right-click the body of the form and click View Code
  8. Right-click in the Code Editor and click Remove and Sort Usings

A Void Function

The creation of a function starts with some options. Later, we will learn more about them in next sections and lessons. For a simple function, specify the option with the void keyword.

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 writteen 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 HelpMe
(
)

Or like this:

void HelpMe(
           )

Or like this:

void HelpMe
     (
     )

The Body of a Function

The body of a function follows the parentheses. After the parentheses, add some brackets { and }. 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 a Fuction

  1. Change the code as follows:
    using System.Windows.Forms;
    
    namespace SalaryEvaluation1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void PresentValues()
            {
                double hourlySalary = double.Parse(txtHourlySalary.Text);
    
                double dailySalary = hourlySalary * 8;
                double weeklySalary = hourlySalary * 40;
                double biweeklySalary = weeklySalary * 2;
                double monthlySalary = weeklySalary * 4;
                double yearlySalary = monthlySalary * 12;
    
                txtDailySalary.Text = dailySalary.ToString();
                txtWeeklySalary.Text = weeklySalary.ToString();
                txtBiweeklySalary.Text = biweeklySalary.ToString();
                txtMonthlySalary.Text = monthlySalary.ToString();
                txtYearlySalary.Text = yearlySalary.ToString();
            }
        }
    }
  2. Click the Form1.cs [Design] tab to access the form
  3. On the form, double-click the Calculate button

Calling a Function

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

Practical LearningPractical Learning: Calling a Function

  1. Implement the event as follows:
    using System.Windows.Forms;
    
    namespace SalaryEvaluation1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void PresentValues
                 (
                 )
            {
                double hourlySalary = double.Parse(txtHourlySalary.Text);
    
                double dailySalary = hourlySalary * 8;
                double weeklySalary = hourlySalary * 40;
                double biweeklySalary = weeklySalary * 2;
                double monthlySalary = weeklySalary * 4;
                double yearlySalary = monthlySalary * 12;
    
                txtDailySalary.Text = dailySalary.ToString();
                txtWeeklySalary.Text = weeklySalary.ToString();
                txtBiweeklySalary.Text = biweeklySalary.ToString();
                txtMonthlySalary.Text = monthlySalary.ToString();
                txtYearlySalary.Text = yearlySalary.ToString();
            }
    
            private void btnCalculate_Click(object sender, System.EventArgs e)
            {
                PresentValues();
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    Calling a Function

  3. In the Hourly Salary text box, type 22.38
  4. Click the Calculate button:

    Material Bar - Emission

  5. Close the form and return to your programming environment
  6. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  7. In the list of projects templates, click Windows Forms App (.NET Framework)
  8. Click Next
  9. Change the project Name to WaterCompany5
  10. Click Create
  11. Design the form as follows:

    Water Distribution Company - Bill Preparation

    Control (Name) Text
    Label   Meter Reading Start . . . . . . . . . . . .
    TextBox txtMeterReadingStarStart 0
    Label   Gallons
    Label   Meter Reading End . . . . . . . . . . . .
    TextBox txtMeterReadingStarEnd 0
    Label   Gallons
    Button btnCalculateWaterAndSewerUsage Calculate Water and Sewer Usage
    Label   _______________________________
    Label   Water and Sewer Usage . . . . . . . . . . . .
    TextBox txtWaterSewerUsage 0
    Label   Gallons
    Label   Water Use Charges => 4.18 per 1,000 Gallons . . . . . . . . . . . . . . . . . . . . . .
    TextBox txtSewerUseCharges 0.00
    Label   Sewer Use Charges => 5.85 per 1,000 Gallons . . . . . . . . . . . . . . . . . . . . .
    TextBox txtSewerUseCharges 0.00
  12. On the form, double-click the Calculate Water and Sewer Usage button
  13. To create another function and call it, change the document as follows:
    using System.Windows.Forms;
    
    namespace WaterCompany5
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void CalculteWaterSewer()
            {
                double usage;
    
                double meterReadingStart = int.Parse(txtMeterReadingStart.Text);
                double meterReadingEnd = int.Parse(txtMeterReadingEnd.Text);
    
                usage = meterReadingEnd - meterReadingStart;
    
                double waterConsumption = (usage * 4.18) / 1000;
                double sewerServices = (usage * 5.85) / 1000;
    
                txtWaterSewerUsage.Text = usage.ToString();
                txtWaterUseCharges.Text = waterConsumption.ToString("F");
                txtSewerUseCharges.Text = sewerServices.ToString("F");
            }
    
            private void btnCalculateWaterAndSewerUsage_Click(object sender, System.EventArgs e)
            {
                CalculteWaterSewer();
            }
        }
    }
  14. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Water Distribution Company - Bill Preparation

  15. In the top text box, type a large number of gallons such as 4017
  16. In the second text box, type a number higher than the first one, such as 6249
  17. Click the top Calculate button:

    Applying the Division

  18. Change the design of the form as follows:

    Water Distribution Company - Bill Preparation

    Control (Name) Text
    Label   Meter Reading Start . . . . . . . . . . . .
    TextBox txtMeterReadingStarStart 0
    Label   Gallons
    Label   Meter Reading End . . . . . . . . . . . .
    TextBox txtMeterReadingStarEnd 0
    Label   Gallons
    Button btnCalculateWaterAndSewerUsage Calculate Water and Sewer Usage
    Label   _______________________________
    Label   Water and Sewer Usage . . . . . . . . . . . .
    TextBox txtWaterSewerUsage 0
    Label   Gallons
    Label   Water Use Charges => 4.18 per 1,000 Gallons . . . . . . . . . . . . . . . . . . . . . .
    TextBox txtSewerUseCharges
    Label   Sewer Use Charges => 5.85 per 1,000 Gallons . . . . . . . . . . . . . . . . . . . . .
    TextBox txtSewerUseCharges
    Label   Distribution Charges . . . . . . . . . . . . . .
    TextBox txtDistributionCharges 0.00
    Label   Environment Charges . . . . . . . . . . . . . .
    TextBox txtEnvironmentCharges 0.00
    Button btnCalculateTotalCharges Calculate Total Charges
    Label   _______________________________
    Label   Total Charges . . . . . . . . . . . .
    TextBox txtTotalCharges
  19. Click the Form1.cs tab to access the code of the form

A Function that Returns a Value

A Function that Returns Nothing

Practially every 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:

class Exercise
{
	void Communicate()
    {
    	return;
    }
    
    void NeedToDiscuss()
    {
    	return;
    }
    
	static void Main()
    {
    	return;
    }
}

Introduction to Returning a Value

Sometimes, you will want a function that gives back a value from its operation(s). To start, when creating the function, on the left side of the name of the function, instead of void, write the data type of the value that the function will produce. Here is an example:

int Calculate()
{
}

In the body of the function, perform the necessary operation. Before the closing curly bracket, type the return keyword, followed by the value the function must return, and end the statement with a semicolon.

Practical LearningPractical Learning: Returning a Value from a Function

  1. Create a new function as follows:
    using System.Windows.Forms;
    
    namespace WaterCompany5
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void CalculteWaterSewer(
                                   )
            {
                double usage;
    
                double meterReadingStart = int.Parse(txtMeterReadingStart.Text);
                double meterReadingEnd = int.Parse(txtMeterReadingEnd.Text);
    
                usage = meterReadingEnd - meterReadingStart;
    
                double waterConsumption = (usage * 4.18) / 1000;
                double sewerServices = (usage * 5.85) / 1000;
    
                txtWaterSewerUsage.Text = usage.ToString();
                txtWaterUseCharges.Text = waterConsumption.ToString("F");
                txtSewerUseCharges.Text = sewerServices.ToString("F");
            }
    
            private void btnCalculateWaterAndSewerUsage_Click(object sender, System.EventArgs e)
            {
                CalculteWaterSewer();
            }
    
            double CalculateSewerUsage()
            {
                double amountDue;
                double waterUseCharges;
                double sewerUseCharges;
                double distributionCharges;
                double environmentCharges;
    
                waterUseCharges = double.Parse(txtWaterUseCharges.Text);
                sewerUseCharges = double.Parse(txtSewerUseCharges.Text);
                distributionCharges = double.Parse(txtDistributionCharges.Text);
                environmentCharges = double.Parse(txtEnvironmentCharges.Text);
    
                amountDue = waterUseCharges + sewerUseCharges + distributionCharges + environmentCharges;
    
                return amountDue;
            }
        }
    }
  2. Click the Form1.cs [Design] tab to access the form

Calling a Function that Returns a Value

You can call a function that returns a value as you do for one that is void. If you want to get and use the value returned by the function, you can declare a variable of the return type and assign the call to that variable. The variable would then be carrying the return value of the function and you can use that value any way you want.

ApplicationPractical Learning: Calling a Function that Returns a Value

  1. On the form, double-click the Calculate Total Charges button
  2. In the event, call the function as follows:
    using System.Windows.Forms;
    
    namespace WaterCompany5
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void CalculteWaterSewer
                                   (
                                   )
            {
                double usage;
    
                double meterReadingStart = int.Parse(txtMeterReadingStart.Text);
                double meterReadingEnd = int.Parse(txtMeterReadingEnd.Text);
    
                usage = meterReadingEnd - meterReadingStart;
    
                double waterConsumption = (usage * 4.18) / 1000;
                double sewerServices = (usage * 5.85) / 1000;
    
                txtWaterSewerUsage.Text = usage.ToString();
                txtWaterUseCharges.Text = waterConsumption.ToString("F");
                txtSewerUseCharges.Text = sewerServices.ToString("F");
            }
    
            private void btnCalculateWaterAndSewerUsage_Click(object sender, System.EventArgs e)
            {
                CalculteWaterSewer();
            }
    
            double CalculateSewerUsage()
            {
                double amountDue;
                double waterUseCharges;
                double sewerUseCharges;
                double distributionCharges;
                double environmentCharges;
    
                waterUseCharges = double.Parse(txtWaterUseCharges.Text);
                sewerUseCharges = double.Parse(txtSewerUseCharges.Text);
                distributionCharges = double.Parse(txtDistributionCharges.Text);
                environmentCharges = double.Parse(txtEnvironmentCharges.Text);
    
                amountDue = waterUseCharges + sewerUseCharges + distributionCharges + environmentCharges;
    
                return amountDue;
            }
    
            private void btnCalculateTotalCharges_Click(object sender, System.EventArgs e)
            {
                double invoice = CalculateSewerUsage();
    
                txtTotalCharges.Text = invoice.ToString();
            }
        }
    }
  3. To execute the application, on the main menu, click Debug -> Start Without Debugging
  4. In the top text box, type a large number of gallons such as 4017
  5. In the second text box, type a number higher than the first one, such as 6249
  6. Click the top Calculate button
  7. In the Distribution Charges text box, type a number such as 12.57
  8. In the Environment Charges text box, type a number such as 24.83
  9. Click the bottom Calculate button
  10. Close the form and return to your programming environment
  11. You first declare a variable if you think that will need to use the value of the function many times. If you will need to use the value returned by the function only once, you may not need a variable. You can call the function directly where its value is returned. For an example, change the code as follows:
    using System.Windows.Forms;
    
    namespace WaterCompany5
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void CalculteWaterSewer()
            {
                . . .
            }
    
            private void btnCalculateWaterAndSewerUsage_Click(object sender, System.EventArgs e)
            {
                CalculteWaterSewer();
                
                // The following line is optional
                return;
            }
    
            double CalculateSewerUsage()
            {
                . . .
    
                return amountDue;
            }
    
            private void btnCalculateTotalCharges_Click(object sender, System.EventArgs e)
            {
                txtTotalCharges.Text = CalculateSewerUsage().ToString();
                
                // The following line is optional
                return;
            }
        }
    }
  12. To execute, press Ctrl + F5
  13. Close the form and return to your programming environment
  14. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  15. In the Create a New Project dialog box, in the list of projects templates, click Windows Forms App (.NET Framework)
  16. Click Next
  17. Change the name to SalaryEvaluation2
  18. Click Create
  19. Design the form as follows:

    Functions Fundamentals

    Control (Name) Text
    Label   Hourly Salary:
    TextBox txtHourlySalary 0.00
    Button btnCalculate Calculate
    Label   _______________________
    Label   Daily Salary:
    TextBox txtDailySalary  
    Label   Weekly Salary:
    TextBox txtWeeklySalary  
    Label   Biweekly Salary:
    TextBox txtBiweeklySalary  
    Label   Monthly Salary:
    TextBox txtMonthlySalary  
    Label   Yearly Salary:
    TextBox txtYearlySalary  
  20. On the form, double-click the Calculate button
  21. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace SalaryEvaluation2
    {
        public partial class Form1 : Form
        {
            double hourlySalary;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            double EvaluateDailyWages()
            {
                return hourlySalary * 8;
            }
    
            double EvaluateWeeklyWages()
            {
                return hourlySalary * 40;
            }
    
            double EvaluateBiweeklyWages()
            {
                return EvaluateWeeklyWages() * 2;
            }
    
            double EvaluateMonthlyWages()
            {
                return EvaluateWeeklyWages() * 4;
            }
    
            double EvaluateYearlyWages()
            {
                return EvaluateMonthlyWages() * 12;
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                hourlySalary = double.Parse(txtHourlySalary.Text);
    
                double dailySalary = EvaluateDailyWages();
                double weeklySalary = EvaluateWeeklyWages();
                double biweeklySalary = EvaluateBiweeklyWages();
                double monthlySalary = EvaluateMonthlyWages();
                double yearlySalary = EvaluateYearlyWages();
    
                txtDailySalary.Text = dailySalary.ToString();
                txtWeeklySalary.Text = weeklySalary.ToString();
                txtBiweeklySalary.Text = biweeklySalary.ToString();
                txtMonthlySalary.Text = monthlySalary.ToString();
                txtYearlySalary.Text = yearlySalary.ToString();
            }
        }
    }
  22. To execute, on the main menu, click Debug -> Start Without Debugging:

    Calling a Function

  23. In the Hourly Salary text box, type 22.38
  24. Click the Calculate button:

    Material Bar - Emission

  25. Close the form and return to your programming environment
  26. Remember that you usually declare a variable for the return value of a function if you are planning to use the value (and/or its variable) many times. Otherwise, you may not need the variable, in which case you can call the function directly where you need it. For examples, change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace SalaryEvaluation2
    {
        public partial class Form1 : Form
        {
            double hourlySalary;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            . . .
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                hourlySalary = double.Parse(txtHourlySalary.Text);
    
                txtDailySalary.Text = EvaluateDailyWages().ToString();
                txtWeeklySalary.Text = EvaluateWeeklyWages().ToString();
                txtBiweeklySalary.Text = EvaluateBiweeklyWages().ToString();
                txtMonthlySalary.Text = EvaluateMonthlyWages().ToString();
                txtYearlySalary.Text = EvaluateYearlyWages().ToString();
                
                // The following line is optional
                return;
            }
        }
    }

A Simple Returning Method With no Body

If you have a function that either contains only one expression or the contents of its body can be resumed to one line, such a function doesn't need a body. Instead, after the parentheses of the function, type => followed by the returning expression.

ApplicationPractical Learning: Creating a Method without a Body

  1. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace SalaryEvaluation2
    {
        public partial class Form1 : Form
        {
            double hourlySalary;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            double EvaluateDailyWages() => hourlySalary * 8;
    
            double EvaluateWeeklyWages() => hourlySalary * 40;
            
            double EvaluateBiweeklyWages()
            {
                return EvaluateWeeklyWages() * 2;
            }
    
            double EvaluateMonthlyWages()
            {
                return EvaluateWeeklyWages() * 4;
            }
    
            double EvaluateYearlyWages()
            {
                return EvaluateMonthlyWages() * 12;
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                hourlySalary = double.Parse(txtHourlySalary.Text);
    
                txtDailySalary.Text = EvaluateDailyWages().ToString();
                txtWeeklySalary.Text = EvaluateWeeklyWages().ToString();
                txtBiweeklySalary.Text = EvaluateBiweeklyWages().ToString();
                txtMonthlySalary.Text = EvaluateMonthlyWages().ToString();
                txtYearlySalary.Text = EvaluateYearlyWages().ToString();
            }
        }
    }
  2. To test the project, press Ctrl + F5
  3. Close the form and return to your programming environment
  4. In the same way, you can call other functions in the returned expression of the one-line function. For examples, change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace SalaryEvaluation2
    {
        public partial class Form1 : Form
        {
            double hourlySalary;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            double EvaluateDailyWages() => hourlySalary * 8;
    
            double EvaluateWeeklyWages() => hourlySalary * 40;
            
            double EvaluateBiweeklyWages() => EvaluateWeeklyWages() * 2;
    
            double EvaluateMonthlyWages() => EvaluateWeeklyWages() * 4;
    
            double EvaluateYearlyWages() => EvaluateMonthlyWages() * 12;
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                hourlySalary = double.Parse(txtHourlySalary.Text);
    
                txtDailySalary.Text = EvaluateDailyWages().ToString();
                txtWeeklySalary.Text = EvaluateWeeklyWages().ToString();
                txtBiweeklySalary.Text = EvaluateBiweeklyWages().ToString();
                txtMonthlySalary.Text = EvaluateMonthlyWages().ToString();
                txtYearlySalary.Text = EvaluateYearlyWages().ToString();
            }
        }
    }
  5. To execute, on the main menu, click Debug -> Start Without Debugging
  6. Close the form and return to Microsoft Visual Studio
  7. Close Microsoft Visual Studio

Previous Copyright © 2001-2021, C# Key Next