Methods Fundamentals

Introduction

A method is a function that is a member of a class. A method follows the exact same descriptions and rules we reviewed for functions. In our lessons, sometimes we may use the words "function" and "method" interchangeably; just keep in mind that a method is a function that is in a class. We also say that a method is a function that belongs to a class, or that a method belongs to a class.

Practical LearningPractical Learning: Introducing Classes

  1. Start Microsoft Visual Studio and create a new C# Console App that supports the .NET 7.0 (Standard Term Support) named PieceWork4
  2. To create a new folder, in the Solution Explorer, right-click PieceWork4 -> Add -> New Folder
  3. Type Models as the name of the new folder
  4. To create a new class, in the Solution Explorer, click Models -> Add -> Class...
  5. In the middle list of the Add New Item dialog box, make sure Class is selected.
  6. Change the file name to Driver
  7. Click Add
  8. Change the document as follows:
    namespace PieceWork4.Models
    {
        public class Driver
        {
        	public string first_name;
        	public string last_name;
        }
    }
  9. To create a new class, in the Solution Explorer, right-click Models -> Add -> Class...
  10. In the middle list, make sure Class is selected.
    Change the Name to Truck
  11. Click Add
  12. Change the document as follows:
    /* Piecework is the type of work that is paid on the number 
     * of items produced, the distance driven, etc.
     * In this exercise, a business uses trucks driven by some 
     * employees or contractors to deliver some products. 
     * The drivers are paid based on the distance they travel to 
     * deliver one or many products. */
    namespace PieceWork4.Models
    {
        public class Truck
        {
        	public string make;
        	public string model;
        }
    }
  13. In the Solution Explorer, right-click Program.cs and click Rename
  14. Type PieceDelivery (to get PieceDelivery.cs) and press Enter twice
  15. Change the PieceDelivery.cs document as follows:
    using PieceWork4;
    using static System.Console;
    
    int miles;
    double pieceworkRate;
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    
    Truck trk = new Truck();
    
    WriteLine("You must provide the information about the truck");
    Write("Make:              ");
    trk.make = ReadLine();
    Write("Model:             ");
    trk.model = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    Driver drv = new Driver();
    
    WriteLine("You must provide the information about the truck driver");
    Write("First Name:        ");
    drv.first_name = ReadLine();
    Write("Last Name:         ");
    drv.last_name = ReadLine();
    WriteLine("-----------------------------------------------------------");

Creating a Method

As seen with functions, the primary formula to create a method is:

options return-type method-name(){}

The main difference between a function and a method is that a method must be created in the body of a class. Here is an example:

class Vehicle
{
    void CarryMe()
    {
    }
}
Author Note

New Convention:

From now on, in our lessons, to refer to a method of a class, we may use the convention:

class-name.method-name()

This means that we are referring to the method method-name that is a function-member of the class class-name.

Practical LearningPractical Learning: Creating Methods

  1. Change the PieceDelivery.cs document as follows:
    using PieceWork4.Models;
    using static System.Console;
    
    int miles;
    double pieceworkRate;
    
    // A method that requests a value
    void GetMiles()
    {
        Write("Miles Driven:   ");
        miles = int.Parse(ReadLine());
    }
    
    // A method that requests a value
    void GetWorkRate()
    {
        Write("Piecework Rate: ");
        pieceworkRate = double.Parse(ReadLine());
    }
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    
    Truck trk = new Truck();
    
    WriteLine("You must provide the information about the truck");
    Write("Make:              ");
    trk.make = ReadLine();
    Write("Model:             ");
    trk.model = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    Driver drv = new Driver();
    
    WriteLine("You must provide the information about the truck driver");
    Write("First Name:        ");
    drv.first_name = ReadLine();
    Write("Last Name:         ");
    drv.last_name = ReadLine();
    WriteLine("-----------------------------------------------------------");

Calling a Method

If you create a method, other members, including methods, of the same class can access that method directly. In the previous lessons, we saw that, before accessing a member of a class, first create an object of that class. On that object, type a period and the desired member. This also applies to a method, except that a method must use parentheses. Accessing a method is also referred to as calling it.

Practical LearningPractical Learning: Calling Methods

  1. Change the document as follows:
    using PieceWork4.Models;
    using static System.Console;
    
    int miles;
    double pieceworkRate;
    
    // A method that requests a value
    void GetMiles()
    {
        Write("Miles Driven:   ");
        miles = int.Parse(ReadLine());
    }
    
    // A method that requests a value
    void GetWorkRate()
    {
        Write("Piecework Rate: ");
        pieceworkRate = double.Parse(ReadLine());
    }
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    
    Truck trk = new Truck();
    
    WriteLine("You must provide the information about the truck");
    Write("Make:              ");
    trk.make = ReadLine();
    Write("Model:             ");
    trk.model = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    Driver drv = new Driver();
    
    WriteLine("You must provide the information about the truck driver");
    Write("First Name:        ");
    drv.first_name = ReadLine();
    Write("Last Name:         ");
    drv.last_name = ReadLine();
    WriteLine("-----------------------------------------------------------");
    
    WriteLine("Enter the values for the delivery");
    GetMiles();
    GetWorkRate();
    
    WriteLine("===========================================================");
    WriteLine(" - Piece Work Delivery -");
    WriteLine("===========================================================");
    WriteLine("Driver:            " + drv.first_name + " " + drv.last_name);
    WriteLine("Truck Details:     " + trk.make + " " + trk.model);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Miles Driven:      {0}", miles);
    WriteLine("Piecework Rate:    {0}", pieceworkRate);
    WriteLine("Gross Salary:      {0}", miles * pieceworkRate);
    WriteLine("===========================================================");
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the First Name as Jeannette and press Enter
  4. For the Last Name, type Dumont and press Enter
  5. For the Make, type Chevrolet and press Enter
  6. For the Model, type LCF 4500 Regular Cab 4x2 and press Enter
  7. For the number of Miles, type 1417 and press Enter
  8. For the Piecework Rate, type .47 and press Enter
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    You must provide the information about the truck driver
    First Name:        Jeannette
    Last Name:         Dumont
    -----------------------------------------------------------
    You must provide the information about the truck
    Make:              Chevrolet
    Model:             LCF 4500 Regular Cab 4x2
    -----------------------------------------------------------
    Enter the values for the delivery
    Miles Driven:      1417
    Piecework Rate:    .47
    ===========================================================
     - Piece Work Delivery -
    ===========================================================
    Driver:            Jeannette Dumont
    Truck Details:     Chevrolet LCF 4500 Regular Cab 4x2
    -----------------------------------------------------------
    Miles Driven:      1417
    Piecework Rate:    0.47
    Gross Salary:      665.99
    ===========================================================
    
    Press any key to close this window . . .
  9. From the File menu, create a new C# Console Application (that supports .NET 7.0 (Standard Term Support)) named PieceWork5
  10. To create a new folder, in the Solution Explorer, right-click PieceWork5 -> Add -> New Folder
  11. Type Models as the name of the folder
  12. To start a class, in the Solution Explorer, click Models -> Add -> Class...
  13. In the middle list of the Add New Item dialog box, make sure Class is selected.
    Change the file name to Contractor
  14. Click Add
  15. Change the document as follows:
    using static System.Console;
    
    namespace PieceWork5.Models
    {
        public class Contractor
        {
            private int number;
    
            void Identify()
            {
                if (number == 485_066)
                {
                    WriteLine("Employee Number:      {0}", number);
                    WriteLine("Contractor Name:      Charles Dunn");
                }
                else if (number == 283_504)
                {
                    WriteLine("Employee Number:      {0}", number);
                    WriteLine("Contractor Name:      Michael Roonney");
                }
                else if (number == 927_284)
                {
                    WriteLine("Employee Number:      {0}", number);
                    WriteLine("Contractor Name:      Carole Griffin");
                }
                else
                {
                    WriteLine("Employee Number:      0");
                    WriteLine("Contractor Name:      Unknown");
                }
            }
        }
    }

The Access Modifier of a Method

As mentioned in previous lessons, if you want a member of a class, including a method, to be accessed outside that class, you must mark that member with an appropriate access level. As a result, when creating a method, the primary option you can provide is its access level. Like any member of a class:

Here is an example of a method marked with an access level and accessed outside the class:

Vehicle transport = new Vehicle();

transport.CarryMe();

public class Vehicle
{
    internal void CarryMe()
    {
    }
}

Practical LearningPractical Learning: Setting the Access Modifier of a Method

The Scope and Lifetime of an Object

In our introduction to functions, we saw that a variable can be declared in the body directly in the document of a Code Editor. Such a variable is said to be global. We also saw that a variable can be declared in the body of a function. Such a variable is said to be local.

You can declare a variable of a class in the body of a class and initialize it there. Here is an example:

public class Student
{
}

public class StudentRegistration
{
    Student pupil = new Student();
    
    private void Show()
    {
    }
}

Once this has been done, the variable can be used in any method of the same class. As an alternative, you can declare the variable in the body of the class but initialize it in a method of the class. Here is an example:

public class Student
{
}

public class StudentRegistration
{
    Student pupil;
    
    void Create()
    {
        pupil = new Student();
    }
    
    void Show()
    {
    }
}

If you decide to use this technique, before the variable can be used, you must call the method that initializes the variable, otherwise you may receive an error.

Classes with Region Delimiters

As seen with functions, the Code Editor of Microsoft Visual Studio allows you to use regional code delimiters to identify the start and end of some sections of code. This also applies to classes and their members such as methods. When you create a class, its start line is automatically marked with a - (minus) button with a vertical line under that button. That vertical line stops where the closing curly bracket is. Here are examples of classes:

Code Editor

As mentioned with functions, to collapse the section of a class, you can click the - button (dash), which changes the button into +. Here is an example:

Code Editor

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

As seen with functions, you can create your own sections. To to this, in the Code Editor of Microsoft Visual Studio, start the section with:

#region Whatever

and end it with:

#endregion Whatever

Here is an example:

class Circle
{
}

#region This section is reserved for quadrilateral shapes
class Rectangle
{
}

class Square
{
}
#endregion This is the end of the quadrilateral section

class Line
{
}

You can also use a Code Snippet to create a region.

Methods and Parameters

A Method with a Parameter

Like a function, a method of a class can use a parameter. When creating the method, make sure you provide the data type of the parameter and its name in the parentheses of the method. When calling the method from an object of the class, make sure you pass an appropriate value as argument.

Practical LearningPractical Learning: Introducing the Parameters of a Method

  1. Change the Contractor class as follows:
    using static System.Console;
    
    namespace PieceWork5.Models
    {
        public class Contractor
        {
            private int number;
    
            public void Initialize(int emplNbr)
            {
                number = emplNbr;
            }
    
            public void Identify()
            {
                if (number == 485_066)
                {
                    WriteLine("Employee Number:      {0}", number);
                    WriteLine("Contractor Name:      Charles Dunn");
                }
                else if (number == 283_504)
                {
                    WriteLine("Employee Number:      {0}", number);
                    WriteLine("Contractor Name:      Michael Roonney");
                }
                else if (number == 927_284)
                {
                    WriteLine("Employee Number:      {0}", number);
                    WriteLine("Contractor Name:      Carole Griffin");
                }
                else
                {
                    WriteLine("Employee Number:      0");
                    WriteLine("Contractor Name:      Unknown");
                }
            }
    
            public void PreparePay(int total)
            {
                double first100;
                double s100To150;
                double over150;
    
                if(total is <= 100)
                {
                    first100  = total * 2.10;
                    s100To150 = 0.00;
                    over150   = 0.00;
                }
                else if( (total is > 100) && (total is <= 150) )
                {
                    first100  = 100 * 2.10;
                    s100To150 = (total - 100) * 2.25;
                    over150 = 0.00;
                }
                else // if (total is > 150))
                {
                    first100 = 100 * 2.10;
                    s100To150 = 50 * 2.25;
                    over150 = (total - 150) * 2.40;
                }
    
                double netPay = first100 + s100To150 + over150;
    
                if( (number == 485_066) || (number == 283_504) || (number == 927_284) )
                    WriteLine("Net Pay:              {0:F}", netPay);
                else
                    WriteLine("Net Pay:              0.00");
            }
        }
    }
  2. In the Solution Explorer, rename Program.cs as UnitsAssembly (to get UnitsAssembly.cs)
  3. Access the UnitsAssembly.cs document and change it as follows:
    using PieceWork5.Models;
    using static System.Console;
    
    WriteLine("Sunshine Electric Company");
    WriteLine("=======================================");
    Write("Type Contractor Code: ");
    int nbr = int.Parse(ReadLine());
    Write("Units Assembled:      ");
    int assembled = int.Parse(ReadLine());
    
    Contractor work = new Contractor();
    work.Initialize(nbr);
    
    WriteLine("=======================================");
    WriteLine("Sunshine Electric Company");
    WriteLine("=======================================");
    work.Identify();
    work.PreparePay(assembled);
    WriteLine("=======================================");
  4. To execute, on the main menu, click Debug -> Start Without Debugging
  5. Type the Contractor Code as 283504 and press Enter
  6. Type the Units Assembled as 248 and press Enter:
    Sunshine Electric Company
    =======================================
    Type Contractor Code: 283504
    Units Assembled:      248
    =======================================
    Sunshine Electric Company
    =======================================
    Employee Number:      283504
    Contractor Name:      Michael Roonney
    Net Pay:              557.70
    =======================================
    
    Press any key to close this window . . .
  7. Close the window and return to your programming environment
  8. To execute again, on the main menu, click Debug -> Start Without Debugging
  9. Type the Contractor Code as 485966 and press Enter
  10. Type the Units Assembled as 317 and press Enter:
    Sunshine Electric Company
    =======================================
    Type Contractor Code: 485966
    Units Assembled:      317
    =======================================
    Sunshine Electric Company
    =======================================
    Employee Number:      0
    Contractor Name:      Unknown
    Net Pay:              0.00
    =======================================
    
    Press any key to close this window . . .
  11. Close the window and return to your programming environment

A Method that Returns a Value

Introduction

Practically every function or method has a body, which is delimited by curly brackets. As seen with functions, to indicate the end of execution of a method, type the return keyword followed by a semicolon. Here are examples:

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

Returning From a Method

Like a function, a method can return a value. If a method doesn't produce an explicit value, mark its return type as void. Otherwise, if a method produces a value, write the desired data type on the left side of the name of the method. Here is an example:

class Rectangle
{
    public double Width;
    public double Height;

    public double Area()
    {
    }
}

Before the closing curly bracket of the method, type the return keyword and what to return, followed by a semicolon.

Like a function, a method can return a constant value. Here is an example:

public class Calculation
{
    int GetTriple()
    {
        return 3000;
    }
}

Otherwise, you can first declare a value and return it from the method. Here is an example:

using static System.Console;

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

        return result;
    }
}

Like a function, a method can return an expression. Consider the above GetTriple method. As seen with functions, if the code of a method is short, you can remove the body of the method delimited by curly brackets. Then, after the parentheses of the method, type => followed by the returning expression and a semicolon. Here is an example:

using static System.Console;

class Numerical
{
    int GetTriple() => nbr * 3;
}

As seen with functions, if you have a method that produces a value that is used only once, you can assign the method to a variable and then use that variable as you see fit. Here are examples:

using static System.Console;

int GetTriple()
{
    return 3000;
}

int value = 3250;

double total = GetTriple();

As seen with functions, if you are not planning to use the returned value of a method many times, you can call the method directly where its value is needed.

As mentioned with functions, instead of storing the returned value of a method in a variable, you can call the method directly on the return line. Here are examples:

using static System.Console;

Exercise exo = new Exercise();

exo.nbr = 44;

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

public class Exercise
{
    public int nbr;

    int Time4()
    {
        return nbr * 4;
    }

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

        return u + w;
    }

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

        return Time4();
    }

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

        return Calculate();
    }
}

ApplicationPractical Learning: Returning From a Method

Calling a Method that Returns a Value

When you call a method that returns a value, you follow the exact same techniques and options we saw for functions. The only difference is that you must qualify the method by an object of its class

ApplicationPractical Learning: Calling a Method on a Local Variable

  1. Click the PieceWork.cs tab
  2. To call some methods and assign their return values to local variables, change the document as follows:
    using PieceWork5.Models;
    using static System.Console;
    
    WriteLine("Sunshine Electric Company");
    WriteLine("=======================================");
    Write("Type Contractor Code: ");
    int nbr = int.Parse(ReadLine());
    Write("Units Assembled:      ");
    int assembled = int.Parse(ReadLine());
    
    Contractor work = new Contractor();
    
    WriteLine("=======================================");
    WriteLine("Sunshine Electric Company");
    WriteLine("-=- Employee Record -=-");
    WriteLine("=======================================");
    string identifier = work.Identify(nbr);
    
    WriteLine("Employee Number:      {0}", nbr);
    WriteLine("Contractor Name:      {0}", identifier);
    
    double netPay = work.PreparePay(assembled);
    
    if ((nbr == 485_066) || (nbr == 283_504) || (nbr == 927_284))
        WriteLine("Net Pay:              {0:F}", netPay);
    else
        WriteLine("Net Pay:              0.00");
    
    WriteLine("=======================================");
  3. To execute, on the main menu, click Debug -> Start Without Debugging
  4. When asked to Type the Contractor Code, type 485066 and press Enter
  5. For the Units Assembled, type 504 and press Enter:
    Sunshine Electric Company
    =======================================
    Type Contractor Code: 485066
    Units Assembled:      504
    =======================================
    Sunshine Electric Company
    =======================================
    Employee Number:      485066
    Contractor Name:      Charles Dunn
    Net Pay:              1172.10
    =======================================
    
    Press any key to close this window . . .
  6. Close the window and return to your programming environment
  7. To call a method directly where it is needed, change the PieceWork.cs document as follows:
    using PieceWork5.Models;
    using static System.Console;
    
    WriteLine("Sunshine Electric Company");
    WriteLine("=======================================");
    Write("Type Contractor Code: ");
    int nbr = int.Parse(ReadLine());
    Write("Units Assembled:      ");
    int assembled = int.Parse(ReadLine());
    
    Contractor work = new Contractor();
    
    WriteLine("=======================================");
    WriteLine("Sunshine Electric Company");
    WriteLine("-=- Employee Record -=-");
    WriteLine("=======================================");
    
    WriteLine("Employee Number:      {0}", nbr);
    WriteLine("Contractor Name:      {0}", work.Identify(nbr));
    
    if ((nbr == 485_066) || (nbr == 283_504) || (nbr == 927_284))
        WriteLine("Net Pay:              {0:F}", work.PreparePay(assembled));
    else
        WriteLine("Net Pay:              0.00");
    
    WriteLine("=======================================");
  8. To execute, on the main menu, click Debug -> Start Without Debugging
  9. When requested, Type the Contrator Code as 927284 and press Enter
  10. Type the Units Assembled as 663 and press Enter:
    Sunshine Electric Company
    =======================================
    Type Contractor Code: 927284
    Units Assembled:      663
    =======================================
    Sunshine Electric Company
    -=- Employee Record -=-
    =======================================
    Employee Number:      927284
    Contractor Name:      Carole Griffin
    Net Pay:              1553.70
    =======================================
    
    Press any key to close this window . . .
  11. Press Enter to close the window and return to your programming environment

Conditional Returns

As mentioned with functions, the returned value of a method may depend on some condition(s). As processing such a condition, you can return the conditional value. If there are many conditions to consider, you can create various conditional statements and return the desired value on each conditional section.

Practical LearningPractical Learning: Conditionally Returning a Value

  1. Click the Contractor.cs tab and, to conditionally return some values from methods, change the class as follows:
    namespace PieceWork5
    {
        public class Contractor
        {
            public string Identify(int number)
            {
                if (number == 485_066)
                    return "Charles Dunn";
                else if (number == 283_504)
                    return "Michael Roonney";
                else if (number == 927_284)
                    return "Carole Griffin";
    
                return "Unknown";
            }
    
            public double PreparePay(int total)
            {
                if(total is <= 100)
                    return total * 2.10;
                else if( (total is > 100) && (total is <= 150) )
                    return (100 * 2.10) + (total - 100) * 2.25;
                else // if (total is > 150))
                    return (100 * 2.10) + (50 * 2.25) + ((total - 150) * 2.40);
    	}
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the Contractor Code as 927284 and press Enter
  4. For the Units Assembled, type 83 and ress Enter:
    Sunshine Electric Company
    =======================================
    Type Contractor Code: 927284
    Units Assembled:      83
    =======================================
    Sunshine Electric Company
    -=- Employee Record -=-
    =======================================
    Employee Number:      927284
    Contractor Name:      Carole Griffin
    Net Pay:              174.30
    =======================================
    
    Press any key to close this window . . .
  5. Press Enter to close the window and return to your programming environment

Nesting a Function

As mentioned with functions, you can create a function inside the body of a method. This is referred to as nesting a function in a method. You primarily create a local function like any other, as long as you create it in the body of another function or method. After creating a nested function, call it by its name as we have done for the others.

Methods and Parameters

Like a function, a method can use external values to perform its actions. Such values are referred to as arguments. To prepare the argument, you must create one or more parameters in the parentheses of the method. As a reminder, a parameter is characterized by a data type and a name. Here is an example:

public class Attachment
{
    void Prepare(int number)
    {
    }
}

In the same way, you can create a method that takes more than one parameter. The parameters are separated by comas. Here are examples:

public class Attachment
{
    void Prepare(int number)
    {
    }

    void Upload(string location)
    {
    }

    void Download(string location, int size)
    {
    }

    void Indicate(int id, string code, int age, double cost)
    {
    }
}
Author Note

New Convention:

From now on, in our lessons, we may write "The syntax of this method is" (or something to that effect):

return-type class-name.method-name(parameter(s));

This means that we are referring to the method method-name that is a member of the class class-name and that uses the parameter(s) specified. We will also provide (or review) the return type of the method.

In our new convention, we may terminate the syntax with a semi-colon.

In the body of a method, you don't have to use a parameter or all parameters. This means that you can completely ignore the parameter. Otherwise, in the body of the method, you can use the parameter in any appropriate way you want.

Method Overloading

Introduction

The signature of a function or method is a combination of its name and the type(s) of its parameter(s), if any. The return type and the symbols (such as the parentheses and the curly brackets) are not part of the signature of a function or method. Since some functions or methods don't take any parameter, the signature of such functions or methods is only the name of the function or method. Consider the following method:

public class
{
    void Consist()
    {
    }
}

The signature of that method is:

Consist

Consider the following method:

public class
{
    double Consist()
    {
    }
}

The signature of that method too is:

Consist

Notice that both methods use the same name. Also notice their return types, void and double. Regardless of the return types, since those methods use the same name and they don't use any parameter, they have the same signature. Consider a method as follows:

public class
{
    int Consist(string characters)
    {
    }
}

If a method uses one parameter, its signature consists of its name and the data type of the parameter, as in:

method-name#parameter-type

As a result, the signature of the above method is:

Count#string

If a method uses two parameters, its signature consists of its name and the data types of the parameters in the order they appear, as in:

method-name#parameter_1-type#parameter_2-type

If a method uses more parameters, its signature consists of its name and the data types of the parameters in the order they appear, as in:

method-name#parameter_1-type#parameter_2-type#parameter_n-type

Practical LearningPractical Learning: Introducing Function Overloading

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. Make sure C# and Console App are selected.
    Click Next
  3. Change the project name to ElementaryAlgebra1 and change or accept the project Location
  4. Click Next
  5. Make sure the Target Framework is displaying .NET 7.0 (Standard Term Support).
    Click Create
  6. To create a new folder, in the Solution Explorer, right-click ElementaryAlgebra1 -> Add -> New Folder
  7. Type Models as the name of the folder
  8. To create a new class, in the Solution Explorer, right-click the second Models -> Add -> Class...
  9. In the middle list of the Add New Item dialog box, make sure Class is selected.
    Change the file Name to Calculations
  10. Click Add
  11. Change the document as follows:
    namespace ElementaryAlgebra1.Models
    {
        public class Calculations
        {
    	public int Add(int a, int b)
        	{
        	    return a + b;
    	}
        }
    }

Overloading a Method

Method overloading is the ability to have two or more methods with the same name in the same class. The primary rule (probably the only rule) is that the overloaded methods cannot have the same signature.

To perform method overloading, each version of the overloaded method must have a different signature. Consider the following class:

public class Geometry
{
    // Square
    double CalculateArea(double side)
    {
    	return side * side;
    }

    // Circle
    double CalculateArea(double radius)
    {
    	return radius * radius * 3.14159;
    }
}

That code will produce an error because both methods have the same signature. There are two main options you can use to solve method overloading issues. One of the solutions to perform method overloading is that the parameters of the methods use different data types. Here is an example:

public class Payroll
{
    double CalculateBiweeklySalary(double yearlySalary)
    {
        return yearlySalary / 24.00;
    }

    // A full-time employee with a fixed yearly salary
    double CalculateBiweeklySalary(string monthlySalary)
    {
        double salary = double.Parse(monthlySalary);

        return monthlySalary / 2.00;
    }
}

Another option is that each method can use a different number of parameters. Based on this, if you insist on having various methods that use the exact same signature, simply add an extra parameter to some of them and don't use that extra parameter in the method.

Practical LearningPractical Learning: Overloading a Method

  1. To overload a method, change the class as follows:
    namespace ElementaryAlgebra1.Models
    {
        public class Calculations
        {
        	public int Add(int a, int b)
            {
    	    return a + b;
        	}
    
            public int Add(int a, int b, int c)
            {
        	    return a + b + c;
            }
    
            public int Add(int a, int b, int c, int d)
            {
        	    return a + b + c + d;
            }
        }
    }
  2. To create another class with an overloaded method, in the Solution Explorer, right-click the second ElementaryAlgebra1 -> Add => Class...
  3. Change the file Name to Presentation
  4. Click Add
  5. Change the document as follows:
    using static System.Console;
    
    namespace ElementaryAlgebra1.Models
    {
        public class Presentation
        {
            private void Display(int x, int y)
            {
                Calculations cals = new Calculations();
    
                int result = cals.Add(x, y);
    
                WriteLine($"Result: {x} + {y} = {result}");
            }
    
            private void Display(int x, int y, int z)
            {
                Calculations cals = new Calculations();
    
                WriteLine($"Result: {x} + {y} + {z} = {cals.Add(x, y, z)}");
            }
    
            private void Display(int u, int v, int w, int x)
            {
                Calculations cals = new Calculations();
    
                int result = cals.Add(u, v, w, x);
    
                WriteLine($"Result: {u} + {v} + {w} + {x} = {result}");
            }
    
            public void Present()
            {
                WriteLine("========================================");
                WriteLine("  =-=-= Elementary Operations =-=-=");
                WriteLine("========================================");
    
                Write("Enter a number:        ");
                int number1 = int.Parse(ReadLine());
                Write("Enter another number:  ");
                int number2 = int.Parse(ReadLine());
                Write("Enter one more Number: ");
                int number3 = int.Parse(ReadLine());
                Write("Enter one more Number: ");
                int number4 = int.Parse(ReadLine());
                WriteLine("=======================================");
                WriteLine("  =-=-= Elementary Operations =-=-=");
                WriteLine("=======================================");
    
                Display(number1, number2);
                WriteLine("---------------------------------------");
                Display(x: number1, y: number2, z: number3);
                WriteLine("---------------------------------------");
                Display(x: number4, u: number1, w: number3, v: number2);
                WriteLine("=====================================");
            }
        }
    }
  6. Click the Program.cs tab and, to overload another function, change the class as follows:
    using ElementaryAlgebra1.Models;
    
    Presentation pres = new Presentation();
    
    pres.Present();
  7. To execute, on the main menu, click Debug -> Start Without Debugging
  8. For the first number, type 10482 and press Enter
  9. For the second number, type 836 and press Enter
  10. For the third number, type 6297 and press Enter
  11. For the fourth number, type 4 and press Enter
    ========================================
      =-=-= Elementary Operations =-=-=
    ========================================
    Enter a number:        10482
    Enter another number:  836
    Enter one more Number: 6297
    Enter one more Number: 4
    =======================================
      =-=-= Elementary Operations =-=-=
    =======================================
    Result: 10482 + 836 = 11318
    ---------------------------------------
    Result: 10482 + 836 + 6297 = 17615
    ---------------------------------------
    Result: 10482 + 836 + 6297 + 4 = 17619
    =======================================
    Press any key to close this window . . .
  12. Press Y to close the window and return to your programming environment
  13. Close your programming environment

Previous Copyright © 2001-2023, C# Key Saturday 29 April 2023 Next