Introduction to External Values on Functions

Using Fields

Sometimes, to perform its operation, a function may need values not available in its body. Such values must be provied one way or another outside the function. One way to solve this problem is to declare one or more variables outside the function, and then use such variable(s) in the function.

Practical LearningPractical Learning: Introducing Functions

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

    Values Conversion - Metric System

    Control (Name) Text
    Label   Side:
    TextBox txtSideInCentimeters 0.00
    Label   Centimeters
    Button btnConvert Convert
    Label   Perimeter:
    TextBox txtSideInInches
    Label   Inches
  7. Right-click the form and click View Code
  8. Right-click in the Code Editor and click Remove and Sort Usings

Introduction to Functions with One Parameter

A function may need to be given a value in other to perform its job. Such a value must be created outside the function. A value that is given to a function is called a paramater. Like a variable, a parameter is represented by a type of value and a name. Therefore, when creating a function that uses a parameter, in the parentheses of the function, enter the data type and the name of the parameter. Here is an example:

void Display(string s)
{

}

In the body of the function, you can ignore or use the parameter. The parameter is used by its name. Here is an example:

void Display(string s)
{
	string message = s;
}

A function that takes a parameter can also return a value. The return type is independent of the parameter. The return type and the parameter can be of the same or different types.

Practical LearningPractical Learning: Introducing Function and their Parameters

  1. Create two functions as follows:
    using System;
    using System.Windows.Forms;
    
    namespace ValuesConversions
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            double ConvertToInches()
            {
                double result;
                double side = double.Parse(txtSideInCentimeters.Text);
    
                result = side * 0.3937;
    
                return result;
            }
    
            void ShowSideInInches(double number)
            {
                txtSideInInches.Text = number.ToString();
            }
        }
    }
  2. Right-click in the Code Editor and click View Designer
  3. On the form, double-click the Convert button
  4. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace ValuesConversions
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            double ConvertToInches()
            {
                double result;
                double side = double.Parse(txtSideInCentimeters.Text);
    
                result = side * 0.3937;
    
                return result;
            }
    
            void ShowSideInInches(double number)
            {
                txtSideInInches.Text = number.ToString();
            }
    
            private void BtnConvert_Click(object sender, EventArgs e)
            {
                double conversion = 0.00;
            }
        }
    }

Calling a Function of One Parameter

To call a function that uses a parameter, you must provide a value for that parameter. The value is supplied in the parentheses of the function that is being called. The value supplied to the function is called an argument. The action of providing that value is called passing an argument to the function.

To pass an argument to a function, you have many options. If you already know the value you want to use, enter it in the parentheses of the function. Here is an example:

void Display(string s)
{
}

void Evaluate()
{
    Display("Welcome to C# Programming!");
}

As an alternative, you can first declare a variable and initialize it with the desired value. You can then pass the name of that variable as argument. The names of the parameters and argument don't have to the same; they can be different. Here is an example:

void Display(string s)
{
}

void Evaluate()
{
    string strMessage = "Welcome to C# Programming!";

	// Blah blah blah
    
    Display(strMessage);
}

Sometimes the value of the argument is created by other means or it is returned by another function. You can first declare a variable to hold that value and pass that variable as argument. Here is an example:

void Display(string s)
{
}

string Create()
{
	return "This is an amazing world.";
}

void Evaluate()
{
    string msg = Create();

	// Blah blah blah
    
    Display(msg);
}

Remember that you usually declare a variable if you are planning to use a certain value many times. If not, you may not need such a variable. In the same way, if the variable is used to get the returned value of a function but you are planning to call that function only once, you can call that function directly where you will need it, including in the parentheses of a function that needs that value. Here is an example:

void Display(string s)
{
}

string Create()
{
	return "This is an amazing world.";
}

void Evaluate()
{
    Display(Create());
}

Practical LearningPractical Learning: Calling a Function of One Parameter

  1. To call the functions you created, change the code of the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace ValuesConversions
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            double ConvertToInches()
            {
                double result;
                double side = double.Parse(txtSideInCentimeters.Text);
    
                result = side * 0.3937;
    
                return result;
            }
    
            void ShowSideInInches(double number)
            {
                txtSideInInches.Text = number.ToString();
            }
    
            private void BtnConvert_Click(object sender, EventArgs e)
            {
                double conversion = ConvertToInches();
    
                ShowSideInInches(conversion);
            }
        }
    }
  2. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging
  3. In the top text box, type a number such as 148.37
  4. Click the button

    Calling a Function of One Parameter

  5. Close the form and return to your programming environment
  6. If you are not planning to call a function many times, or if the value of the variable will not change many times, then there is no need for the variable. You can call the function directly in the parentheses of the called function where the argument is needed.
    Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace ValuesConversions
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            double ConvertToInches()
            {
                double result = double.Parse(txtSideInCentimeters.Text) * 0.3937;
    
                return result;
            }
    
            void ShowSideInInches(double number)
            {
                txtSideInInches.Text = number.ToString();
            }
    
            private void BtnConvert_Click(object sender, EventArgs e)
            {
                ShowSideInInches(ConvertToInches());
            }
        }
    }
  7. To execute the application, on the main menu, click Debug -> Start Without Debugging
  8. In the Side text box, type a number such as 417.58
  9. Click the Convert button
  10. Close the form and return to your programming environment
  11. Since the ConvertToInches() function is short, it doesn't need a formal body. Therefore, change the ConvertToInches() function as follows:
    using System;
    using System.Windows.Forms;
    
    namespace ValuesConversions
    {
        public partial class MetricSystem : Form
        {
            public MetricSystem()
            {
                InitializeComponent();
            }
    
            private double ConvertToInches() => double.Parse(txtSideInCentimeters.Text) * 0.3937;
    
            private void ShowSideInInches(double number)
            {
                txtSideInInches.Text = number.ToString();
            }
    
            private void BtnConvert_Click(object sender, EventArgs e)
            {
                ShowSideInInches(ConvertToInches());
            }
        }
    }
  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 list of projects templates, click Windows Forms App (.NET Framework)
  16. Click Next
  17. Change the project Name to BusinessMathematics1
  18. Click Create
  19. Design the form as follows:

    Values Conversion - Metric System

    Control (Name) Text
    Label   Purchase Price:
    TextBox txtPurchasePrice 0.00
    Label   Tax Rate:
    TextBox txtTaxRate 0.00
    Label   %
    Button btnCalculate Calculate
    Label   Tax Amount:
    TextBox txtTaxAmount
  20. Right-click the form and click View Code
  21. Right-click in the Code Editor and click Remove and Sort Usings

A Function With Many Parameters

Introduction

A function can use as many parameters as you want. Each parameter must have a data type and a name. The parameters can be of the same or different types. The parameters are separated by comas. Here is an example:

class Something
{
    private void ShowResult(string s, double n)
    {
    }
}

Practical LearningPractical Learning: Creating a Function With Many Parameters

  1. To create a function that uses two parameters, type the following code:
    using System.Windows.Forms;
    
    namespace BusinessMathematics1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            
            double CalculateTaxAmount(double price, double rate)
            {
                return price * rate / 100;
            }
        }
    }
  2. Right-click in the Code Editor and click View Designer
  3. On the form, double-click the Calculate button
  4. Implement the event as follows:
    using System.Windows.Forms;
    
    namespace BusinessMathematics1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            
            double CalculateTaxAmount(double price, double rate)
            {
                return price * rate / 100;
            }
    
            private void btnCalculate_Click(object sender, System.EventArgs e)
            {
                double price = double.Parse(txtPurchasePrice.Text);
                double rate = double.Parse(txtTaxRate.Text);
    
                double amount = 0.00;
    
                txtTaxAmount.Text = amount.ToString("F");
            }
        }
    }

Introduction to Calling a Function of Many Parameters

We saw that, when calling a function that takes an argument, you can type a value in the parentheses of the function or you can pass the name of a variable that holds the value to pass. In the same way, when calling a function that takes more than one argument, type the appropriate value in the placeholder of each argument.

ApplicationPractical Learning: Calling a Function of Many Parameters

  1. To call the function, change the code as follows:
    using System.Windows.Forms;
    
    namespace BusinessMathematics1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            
            double CalculateTaxAmount(double price, double rate)
            {
                return price * rate / 100;
            }
    
            private void btnCalculate_Click(object sender, System.EventArgs e)
            {
                double price = double.Parse(txtPurchasePrice.Text);
                double rate = double.Parse(txtTaxRate.Text);
    
                double amount = CalculateTaxAmount(price, rate);
    
                txtTaxAmount.Text = amount.ToString("F");
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. In the Purchase Price text box, type a number such as 380
  4. In the Tax Rate text box, type a number such as 7.25

    Calling a Function of Many Parameters

  5. Click the Calculate button

    Calling a Function of Many Parameters

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

    Values Conversion - Metric System

    Control (Name) Text
    Label   Contractor Code:
    TextBox txtContractorCode
    Label   Hourly Salary:
    TextBox txtHourlySalary 0.00
    Label   First Name
    TextBox txtFirstName
    Label   Last Name
    TextBox txtLastName
    Label   Time Worked - Week 1:
    TextBox txtWeek1TimeWorked 0.00
    Label   Week 2:
    TextBox txtWeek2TimeWorked 0.00
    Button btnShowPayroll Present Payroll
    Label   Contractor Code:
    TextBox txtEmployeeNumber
    Label   Net Pay:
    TextBox txtNetPay
    Label   Employee Name:
    TextBox txtEmployeeName
  13. On the form, double-click the Present Payroll button
  14. Right-click in the Code Editor and click Remove and Sort Usings
  15. Create two functions that takes parameters and implement the event as follows:
    uusing System.Windows.Forms;
    
    namespace PayrollEvaluation1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            string GetContractorName(string fname, string lname)
            {
                return fname + " " + lname;
            }
    
            double CalculateSalary(double salary, double week1Work, double week2Work)
            {
                double totalTimeWorked = week1Work + week2Work;
    
                double biweeklyTotal = salary * totalTimeWorked;
    
                return biweeklyTotal;
            }
    
            private void BtnShowPayroll_Click(object sender, EventArgs e)
            {
                double week1 = double.Parse(txtWeek1TimeWorked.Text);
                double week2 = double.Parse(txtWeek2TimeWorked.Text);
            }
        }
    }
  16. To call the function and pass arguments to it, change the code of the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PayrollEvaluation1
    {
        public partial class Form1 : Form
        {
            public PayrollEvaluation()
            {
                InitializeComponent();
            }
    
            string GetContractorName(string fname, string lname)
            {
                return fname + " " + lname;
            }
    
            double CalculateSalary(double salary, double week1Work, double week2Work)
            {
                double totalTimeWorked = week1Work + week2Work;
    
                double biweeklyTotal = salary * totalTimeWorked;
    
                return biweeklyTotal;
            }
    
            private void btnShowPayroll_Click(object sender, EventArgs e)
            {
                string workCode = txtContractorCode.Text;
                string firstName = txtFirstName.Text;
                string lastName = txtLastName.Text;
                double hSalary = double.Parse(txtHourlySalary.Text);
    
                double week1 = double.Parse(txtWeek1TimeWorked.Text);
                double week2 = double.Parse(txtWeek2TimeWorked.Text);
    
                double salary = CalculateSalary(hSalary, week1, week2);
    
                txtEmployeeNumber.Text = workCode;
                txtEmployeeName.Text = GetContractorName(firstName, lastName);
                txtNetPay.Text = salary.ToString("F");
            }
        }
    }
  17. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Calling a Function of Many Parameters

  18. In the Contractor Code text box, type a number such as 924058
  19. In the Hourly Salary text box, type a number such as 25.50
  20. In the First Name text box, type a name such as Jennifer
  21. In the Last Name text box, type a name such as Cranston
  22. In the Time Worked - Week 1 text box, type a number as 38.50
  23. In the Week 2 text box, type a number such as 44

    Calling a Function of Many Parameters

  24. Click the button

    Calling a Function of Many Parameters

  25. Close the form and return to your programming environment

Accessing a Parameter by Name

If you call a function that takes many arguments, you don't have to use the exact placeholder of each parameter. Instead, you can refer to each argument by the name of its parameter, followed by a colon, and followed by the appropriate value.

ApplicationPractical Learning: Accessing a Parameter by Name

  1. Change the calls to the functions as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PayrollEvaluation1
    {
        public partial class Form1 : Form
        {
            public PayrollEvaluation()
            {
                InitializeComponent();
            }
    
            string GetContractorName(string fname, string lname)
            {
                return fname + " " + lname;
            }
    
            double CalculateSalary(double salary, double week1Work, double week2Work)
            {
                double totalTimeWorked = week1Work + week2Work;
    
                return salary * totalTimeWorked;
            }
    
            private void btnShowPayroll_Click(object sender, EventArgs e)
            {
                string workCode = txtContractorCode.Text;
                string firstName = txtFirstName.Text;
                string lastName = txtLastName.Text;
                double hSalary = double.Parse(txtHourlySalary.Text);
    
                double week1 = double.Parse(txtWeek1TimeWorked.Text);
                double week2 = double.Parse(txtWeek2TimeWorked.Text);
    
                double salary = CalculateSalary(week2Work: week2, week1Work: week1, salary: hSalary);
    
                txtEmployeeNumber.Text = workCode;
                txtEmployeeName.Text = GetContractorName(lname: lastName, fname : firstName);
                txtNetPay.Text = salary.ToString("F");
            }
        }
    }
  2. To execute the application and test the calculations, press Ctrl + F5
  3. Close the form and return to your programming environment
  4. To change the functions in one-line code, change them as tollows:
    using System;
    using System.Windows.Forms;
    
    namespace PayrollEvaluation1
    {
        public partial class Form1 : Form
        {
            public PayrollEvaluation()
            {
                InitializeComponent();
            }
    
            string GetContractorName(string fname, string lname) => fname + " " + lname;
    
            double CalculateSalary(double salary, double week1Work, double week2Work) => salary * (week1Work + week2Work);
    
            private void btnShowPayroll_Click(object sender, EventArgs e)
            {
                string workCode = txtContractorCode.Text;
                string firstName = txtFirstName.Text;
                string lastName = txtLastName.Text;
                double hSalary = double.Parse(txtHourlySalary.Text);
    
                double week1 = double.Parse(txtWeek1TimeWorked.Text);
                double week2 = double.Parse(txtWeek2TimeWorked.Text);
    
                double salary = CalculateSalary(week2Work: week2, week1Work: week1, salary: hSalary);
    
                txtEmployeeNumber.Text = workCode;
                txtEmployeeName.Text = GetContractorName(lname: lastName, fname : firstName);
                txtNetPay.Text = salary.ToString("F");
            }
        }
    }
  5. To execute, on the main menu, click Debug -> Start Without Debugging
  6. Close the form and return to your programming environment
  7. Close Microsoft Visual Studio

Previous Copyright © 2001-2021, C# Key Next