C# Language

The Methods of a Class

When you create a class, the fields are meant to describe it. For a class named House, such aspects as the number of bedrooms, the property type, or its…

20 min read4,462 words46 code samples

Methods Fundamentals#

Introduction#

Defining a class involves specifying fields that represent its characteristics and state.

C#
public class House
{
    public char propertyType;
    public uint bedrooms;
}

In addition to the characteristics that describe it, an object can also carry out actions or tasks. An action carried out by a class is called a function or a method. A method is simply a block of code that handles one specific aspect of the class’s behavior. Application: Introducing Functions

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project
  3. In the middle list, click Empty Project
  4. Change the Name to DepartmentStore2 and click OK
  5. On the main menu, click Project -> Add New Item...
  6. In the middle list of the Add New Item dialog box, click Code File
  7. Change the name to StoreItem and click Add
  8. In the file, type the following: public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; }
  9. To create a code file, in the Solution Explorer, right-click DepartmentStore2 -> Add -> New Item...
  10. In the middle list of the Add New Item dialog box, click Code File
  11. Change the name to DepartmentStore and click Add
  12. In the empty document, type the following: public class DepartmentStore { static void Main() { StoreItem si = new StoreItem(); si.itemNumber = 720823; si.itemName = "Cotton Seam Sheath Dress"; si.size = "6"; si.unitPrice = 158M; System.Console.WriteLine("Department Store"); System.Console.Write("Item #: "); System.Console.WriteLine(si.itemNumber); System.Console.Write("Item Name: "); System.Console.WriteLine(si.itemName); System.Console.Write("Item Size: "); System.Console.WriteLine(si.size); System.Console.Write("Unit Price: "); System.Console.WriteLine(si.unitPrice); System.Console.ReadKey(); } }
  13. Execute the application to see the result
  14. Close the DOS window and return to your programming environment

Creating a Method#

To create a method, specify its name. The name of a method primarily follows the rules we defined for names of variables. Besides those rules, you can add yours. In our lessons, we will follow the same suggestions we reviewed for names of classes:

  • If the name of a method is in one word, the first letter will be in uppercase
  • If the name of a method is a combination of words, the first letter of each word will be in uppercase
  • Because a method is an action, you should name it as a verb

The name of a method is followed by parentheses. A method's job is to carry a specific assignment within a program. As such, it could provide a value once the assignment has been carried. In some cases, a method must produce a result. If it doesn't, then it is considered void. The type of value that a method can provide (or return) is written on the left side of the method name. If the method doesn't produce a result, type void to its left. The assignment that a method carries is included between an opening curly bracket "{" and a closing curly bracket "}". Here is an example:

C#
public class House
{
    public char propertyType;
    public uint bedrooms;

    void Display()
    {
    }
}

The most regularly used method of a C# program is called Main.

New Convention:#

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

C#
ClassName.MethodName

This means that we are referring to the method MethodName that is a member of the class ClassName.

The Access Modifier of a Method#

Like a member variable:

  • If the method will be accessed only by members of the same class, you can mark it as private or not mark it with an access modifier
  • If the method will be accessed by members of the class and other parts of the same program but not outside of the program, mark it with the internal keyword
  • In the method can be accessed by the members of the same class, other parts of the same program, and other parts of other programs, mark it as public

After creating a method, in its body delimited by its curly brackets, you can define the desired behavior. For example, you can write the member variables in the parentheses of System.Console.Write() or System.Console.WriteLine(). Here are examples:

C#
public class House
{
    public char propertyType;
    public uint bedrooms;

    internal void Display()
    {
        System.Console.WriteLine("=//= Altair Realtors =//=");
        System.Console.WriteLine("Properties Inventory"); ;
        System.Console.Write("Property Type:  ");
        System.Console.WriteLine(PropertyType);
        System.Console.Write("Bedrooms:       ");
        System.Console.WriteLine(Bedrooms);
    }
}

In the same way, you can create as many methods as you want in a class.

Accessing a Method#

After creating a method, you can access it outside of its class. You do this following the same rules used to access a field, using the period operator. Unlike a field, the name of a class must be followed by parentheses. Here is an example:

C#
public class House
{
    public char propertyType;
    public uint bedrooms;

    internal void Display()
    {
        System.Console.WriteLine("=//= Altair Realtors =//=");
        System.Console.WriteLine("Properties Inventory"); ;
        System.Console.Write("Property Type:  ");
        System.Console.WriteLine(propertyType);
        System.Console.Write("Bedrooms:       ");
        System.Console.WriteLine(bedrooms);
    }
}

public class Program
{
    static void Main()
    {
        var property = new House();

        property.propertyType = 'S';
        property.bedrooms = 4;

        property.Display();
    }
}

This would produce:

C#
=//= Altair Realtors =//=
Properties Inventory
Property Type:  S
Bedrooms:       4
Press any key to continue . . .

Application: Creating the Methods of a Class

  1. On the main menu, click Window -> StoreItem.cs to open that file
  2. To add some methods to the class, change the document as follows: public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; public void CreateItem() { itemNumber = 792475; itemName = "Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray"; size = "3.4oz"; unitPrice = 48.00m; } public void Describe() { System.Console.WriteLine("Department Store"); System.Console.Write("Item #: "); System.Console.WriteLine(itemNumber); System.Console.Write("Item Name: "); System.Console.WriteLine(itemName); System.Console.Write("Item Size: "); System.Console.WriteLine(size); System.Console.Write("Unit Price: "); System.Console.WriteLine(unitPrice); } }
  3. On the main menu, click Window -> DepartmentStore.cs
  4. Change the document as follows: public class DepartmentStore { static void Main() { StoreItem si = new StoreItem(); si.CreateItem(); si.Describe(); System.Console.ReadKey(); } }
  5. Execute the application. This would produce: Department Store Item #: 792475 Item Name: Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray Item Size: 3.4oz Unit Price: 48.00
  6. Close the DOS window and return to your programming environment

A Method that Returns a Value#

In the body of a method, you can declare one or more variables that would be used only by the method. A variable declared in the body of a method is referred to as a local variable. The variable cannot be accessed outside of the method it belongs to. After declaring a local variable, it is made available to the method and you can use it as you see fit, for example, you can assign it a value prior to using it. If a method has carried an assignment and must make its result available to other methods or other classes, the method must return a value and cannot be void. To declare a method that returns a value, provide its return type to the left of its name. Here is an example:

C#
class Exercise
{
    double Operate()
    {
    }

    static void Main()
    {
    }
}

After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To do this, you use the return keyword followed by the value that the method is returning. The value returned must be of the same type specified as the return type of the method. Here is an example:

C#
class Exercise
{
    double Operate()
    {
	return 24.55;
    }

    static void Main()
    {
    }
}

A method can also return an expression, provided the expression produces a value that is conform to the return type. Here is an example:

C#
class Exercise
{
    double Operate()
    {
	return 24.55 * 4.16;
    }

    static void Main()
    {
    }
}

Application: Returning a Value From a Method

  1. On the main menu, click Window -> StoreItem.cs
  2. Change the file as follows: public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; public void CreateItem() { itemNumber = 792475; itemName = "Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray"; size = "3.4oz"; unitPrice = 48.00m; } public decimal CalculateTotalValue() { return unitPrice; } public void Describe() { System.Console.WriteLine("Department Store"); System.Console.Write("Item #: "); System.Console.WriteLine(itemNumber); System.Console.Write("Item Name: "); System.Console.WriteLine(itemName); System.Console.Write("Item Size: "); System.Console.WriteLine(size); System.Console.Write("Unit Price: "); System.Console.WriteLine(unitPrice); System.Console.Write("Total Value: "); System.Console.WriteLine(CalculateTotalValue()); } }
  3. Execute the application to see the result
  4. Close the DOS window and return to your programming environment

Introduction to the Main Function of an Application#

So far, we have used the Main() function as it is defined by default when you create an application using the New Project dialog box. This default implementation of the Main() function is of type void. Another way to implement the Main() function is to make it return an integer. The rule is the same as for any method of type int. The Main() function can return any type of integer as long as it is a valid integer. Here is an example:

C#
class Exercise
{
    char HaveCharacter()
    {
        return 'G';
    }

    static int Main()
    {
        Exercise exo = new Exercise();

        System.Console.Write("Character: ");
        System.Console.WriteLine(exo.HaveCharacter());

        return 244006;
    }
}

This would produce:

C#
Character: G
Press any key to continue . . .

To create a Main function using skeleton code, right-click the section where you want to add it and click Insert Snippet... Double-click Visual C#:

  • If you want to create a Main function that doesn't return a value, double-click svm (stands for "static void Main")
  • If you want to create a Main function that returns an integer, double-click sim (stands for "static int Main")

Application: Returning a Value From Main()

  1. Click the DepartmentStore.cs button to access it and change it as follows: public class DepartmentStore { static int Main() { StoreItem si = new StoreItem(); si.CreateItem(); si.Describe(); System.Console.ReadKey(); return 0; } }
  2. Execute the application to see the result
  3. Close the DOS window and return to your programming environment

Methods' Arguments#

Introduction#

A method performs an assignment that completes the operations of a class. The methods we used in the previous sections relied on local variables to exchange information with other sections of the program. Sometimes, a method would need one or more values in order to carry its assignment. The particularity of such a value or such values is that another method that calls this one must supply the needed value(s). When a method needs a value to complete its assignment, such a value is called an argument. Like a variable, an argument is represented by its type of value. For example, one method may need a character while another would need a string. Yet another method may require a decimal number. This means that the method or class that calls a method is responsible for supplying the right value, even though a method may have an internal mechanism of checking the validity of such a value. The value supplied to a method is typed in the parentheses of the method and it's called an argument. In order to declare a method that takes an argument, you must specify its name and the argument between its parentheses. Because a method must specify the type of value it would need, the argument is represented by its data type and a name. Suppose you want to define a method that displays the side length of a square. Since you would have to supply the length, you can define such a method as follows:

C#
public class Exercise
{
    void Display(double Length)
    {
    }
}

In the body of the method, you may or may not use the value of the argument. Otherwise, you can manipulate the supplied value as you see fit. In this example, you can display the value of the argument as follows:

C#
public class Exercise
{
    void Display(double Length)
    {
	System.Console.Write("Length: ");
	System.Console.WriteLine(Length);
    }
}

When calling a method that takes an argument, you must supply a value for the argument; otherwise you would receive an error. Also, you should/must supply the right value; otherwise, the method may not work as expected and it may produce an unreliable result. As mentioned already, a method that takes an argument can also declare its own local variable(s). A method can take more than one argument. When defining such a method, provide each argument with its data type and a name. The arguments are separated by a comma.

New Convention:#

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

C#
ClassName.MethodName(Arguments)

This means that we are referring to the method MethodName that is a member of the class ClassName. The item in the parentheses will refer to the argument(s) that the method takes.

New Convention:#

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

C#
ReturnValue ClassName.MethodName(Arguments);

This means that we are providing (reviewing) the return type, the name, and the number of arguments (if any) of a method. In our new convention, we terminate the syntax with a semi-colon. In reality, unlike C, C++, Object Pascal, Visual Basic, and some other languages, C# (and Java) doesn't allow forward definition. That is, you cannot first declare a function, then implement it in another section of the file or in another file (C# supports partial methods but that's not real forward definition, not in the sense of C, Pascal, and Visual Basic). We will use the semi-colon (or the only reason we will use the semi-colon) is to indicate the structure or skeleton of the method, not its actual definition. Application: Passing Arguments

  1. Click the StoreItem.cs button to open its file and change it as follows: public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; public void CreateItem() { itemNumber = 911792; itemName = "Girls Tillie Poplin Dress"; size = "12"; unitPrice = 110.00m; } public decimal CalculateTotalValue( int qty ) { return unitPrice * qty; } public void Describe() { int quantity = 6; System.Console.WriteLine("Department Store"); System.Console.Write("Item #: "); System.Console.WriteLine(itemNumber); System.Console.Write("Item Name: "); System.Console.WriteLine(itemName); System.Console.Write("Item Size: "); System.Console.WriteLine(size); System.Console.Write("Unit Price: "); System.Console.WriteLine(unitPrice); System.Console.Write("Quantity: "); System.Console.WriteLine(quantity); System.Console.Write("Total Value: "); System.Console.WriteLine( CalculateTotalValue( quantity )); } }
  2. Execute the application to see the result: Department Store Item #: 911792 Item Name: Petite Tropical Wool Pencil Skirt Item Size: 12 Unit Price: 110.00 Quantity: 6 Total Value: 660.00
  3. Close the DOS window and return to your programming environment

Techniques of Passing Arguments#

Passing an Argument by Value#

In situations where you invoke a method requiring one or more parameters, you must provide the corresponding values.

Passing an Argument by Reference#

Consider the following program:

C#
public class Exercise
{
    void GetDeposit(decimal amount)
    {
        amount = 450;

        System.Console.WriteLine("In GetDeposit()");
        System.Console.Write("Amouont: $");
        System.Console.WriteLine(amount);
    }

    static int Main()
    {
        decimal amt = 0;
        var exo = new Exercise();

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amouont: $");
        System.Console.WriteLine(amt);

        System.Console.WriteLine("-------------------------");
        exo.GetDeposit(amt);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amouont: $");
        System.Console.WriteLine(amt);

        return 0;
    }
}

This would produce:

C#
In Main()
Amouont: $0
-------------------------
In GetDeposit()
Amouont: $450
-------------------------
Bank in Main()
Amouont: $0
Press any key to continue . . .

Notice that the value of the argument is the same before and after calling the GetDeposit() method. When you declare a variable in a program, the compiler reserves an amount of space for that variable. If you need to use that variable somewhere in your program, you can simply access it and make use of its value. There are two major issues related to a variable: its value and its location in the memory. The location of a variable in memory is referred to as its address. If you supply the argument using its name, the compiler only makes a copy of the argument's value and gives it to the calling method. Although the calling method receives the argument's value and can use it in any way, it cannot (permanently) alter it. An alternative is to call a method to modify the value of an argument if you find it necessary. If you want the calling method to modify the value of a supplied argument and return the modified value, you can pass the argument using its reference. To pass an argument as a reference, when defining the method, precede the argument's data type with the ref keyword. Here is an example:

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
    }
}

In the method, you can use or ignore the argument. When calling the method, precede the argument's name with the ref keyword. here is an example:

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
    }

    static int Main()
    {
        decimal amt = 0;
        var exo = new Exercise();

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        exo.GetDeposit(ref amt);

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        return 0;
    }
}

This would produce:

C#
In Main()
Amount: $0
Bank in Main()
Amount: $0
Press any key to continue . . .

The true purpose of passing an argument by reference is to allow the method to change the value of the argument. To make this possible, in the method, make sure you change the value of the argument. Here is an example:

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
        amount = 450;

        System.Console.WriteLine("In GetDeposit()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amount);
    }

    static int Main()
    {
        decimal amt = 0;
        var exo = new Exercise();

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        System.Console.WriteLine("-------------------------");
        exo.GetDeposit(ref amt);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amt);

        return 0;
    }
}

This would produce:

C#
In Main()
Amount: $0
-------------------------
In GetDeposit()
Amount: $450
-------------------------
Bank in Main()
Amount: $450
Press any key to continue . . .

Notice that this time, the value of the variable is changed after the function has been called. You can pass 0, one, or more arguments as reference in the program or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called method to modify the argument and permanently change its value. When we studied the fact that a method can return a value, we saw that a function can return only one value because there is only one return keyword. Fortunately, the ability to pass many arguments by reference makes it possible for a method to return many values.

Passing an Argument Out#

Another option consists of passing an argument using the out keyword. As done for passing by reference, to pass an argument out, in the parentheses of the method, precede the data type of the argument with the out keyword. Here is an example:

C#
public class Exercise
{
    void GetWithdrawal(out decimal amount)
    {
        
    }
}

The main difference between the ref and the out keywords is that, if you pass an argument with out, you must initialize it (give it a value) in the method, whether you will use the argument in the method or not. Here is an example:

C#
public class Exercise
{
    void GetWithdrawal(out decimal amount)
    {
        amount = 265.00m;
    }
}

When calling a method that takes an out argument, precede the argument with the out keyword. Here is an example:

C#
public class Exercise
{
    void GetDeposit(ref decimal amount)
    {
        amount = 450.00M;

        System.Console.WriteLine("In GetDeposit()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amount);
    }

    void GetWithdrawal(out decimal amount)
    {
        amount = 265.00m;

        System.Console.WriteLine("In GetWithdrawal()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(amount);
    }

    static int Main()
    {
        decimal depositAmount = 0M;
        decimal withdrawalAmount = 0M;
        var exo = new Exercise();

        System.Console.WriteLine("In Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(depositAmount);

        System.Console.WriteLine("-------------------------");
        exo.GetDeposit(ref depositAmount);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(depositAmount);

        System.Console.WriteLine("-------------------------");
        exo.GetWithdrawal(out withdrawalAmount);
        System.Console.WriteLine("-------------------------");

        System.Console.WriteLine("Bank in Main()");
        System.Console.Write("Amount: $");
        System.Console.WriteLine(withdrawalAmount);

        return 0;
    }
}

As done for the ref keyword, if you pass an argument with out, any modification made on the argument would be kept when the method ends. This would produce:

C#
In Main()
Amount: $0
-------------------------
In GetDeposit()
Amount: $450.00
-------------------------
Bank in Main()
Amount: $450.00
-------------------------
In GetWithdrawal()
Amount: $265.00
-------------------------
Bank in Main()
Amount: $265.00
Press any key to continue . . .

As mentioned for a ref argument, a method that receives arguments passed with out can be used to return many values, as opposed to returning only one by using the return keyword.

Method Overloading#

Consider the following function named CalculateArea:

C#
public class Geometry
{
    double CalculateArea()
    {
        return 0D;
    }
}

When you create a method in a class and when you build the project, the compiler creates a list of those methods. This list is called a virtual table. In the table, a method is encoded using its name:

Method NameEncoding
CalculateAreaCalculate@None

If the method has an argument, the table contains the data type of that argument. Neither the return type of the method nor the name(s) of the argument(s) is important. If the class contains methods that have different names, they are easily distinguishable (because they have different names). Sometimes, for one reason or another, you may want to have different methods that do a similar job with slight differences (it will be your job to define what the differences are and why). One way you can indicate that the methods accomplish the same purpose is to have them use the same name. The ability to have two or more methods with the same name in the same class is referred to as method overloading. To perform method overloading, that we will refer to in our lessons as overloading a method, when creating the virtual table, each entry in the list must be unique. As mentioned already, the return type of a method is not entered. So you cannot base the differences on it. If you try creating two methods and none takes an argument, obviously you cannot distinguish them in the table. The solution is that one of them should take an argument. Here is an example:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

    // Square
    public double CalculateArea(double side)
    {
        return side * side;
    }
}
Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double

Obviously this time, each method has a different encoding. Here is an example of using the above code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

public class Exercise
{
    static int Main()
    {
        Geometry geo = new Geometry();

        System.Console.WriteLine("Geometric Shapes");
        System.Console.WriteLine("Calculation of Areas");
        System.Console.Write("Square: ");
        System.Console.WriteLine(geo.CalculateArea(26.38));

        return 0;
    }
}

This would produce:

C#
Geometric Shapes
Calculation of Areas
Square: 695.9044
Press any key to continue . . .

It is important to remember that the specific name of an argument does not impact its method signature. Consider the following code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

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

This would result in:

Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double
CalculateAreadoubleCalculate@Double

As a result, when you build the project, the compiler would produce the following error:

C#
Error	1	Type 'Geometry' already defines a member called 'CalculateArea' 
with the same parameter types	
C:\Users\Administrator\AppData\Local\Temporary Projects\Overloading\Exercise.cs	16	19	Overloading

One of the rules of method overloading is that the method can have different types of arguments. Here is an example:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Circle
    public float CalculateArea(float radius)
    {
        return radius * radius * 3.14159f;
    }
}

In many cases, you will not want to simply pass a different type of argument. We mentioned that, in the virtual table, the data type of the argument is entered. What if each method takes a different number of argument? Consider the following example:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }
}

This would result in:

Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double
CalculateAreadouble, doubleCalculate@Double@Double

Notice that the encoding of the second and the third methods is different. Here is an example of calling the methods:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }
}

public class Exercise
{
    static int Main()
    {
        var geo = new Geometry();

        System.Console.WriteLine("Geometric Shapes");
        System.Console.WriteLine("Calculation of Areas");
        System.Console.Write("Square:    ");
        System.Console.WriteLine(geo.CalculateArea(26.38));
        System.Console.Write("Rectangle: ");
        System.Console.WriteLine(geo.CalculateArea(39.17, 26.38));

        return 0;
    }
}

This would produce:

C#
eometric Shapes
alculation of Areas
quare:    695.9044
ectangle: 1033.3046
ress any key to continue . . .

Although we are using two double arguments for the third methd, the arguments can be of any type. It will be your decision what creating the method. Therefore, another rule of method overloading states that each method must use a different number of argument. One of the characteristics of most computer languages, including C-based languages (C++, Java, C#, etc) and others (Pascal, Visual Basic, etc) is that you don't have to use an argument in its method. You can use this feature to create two versions of a method that should have the same behavior: you can pass an argument that you will not use but that results in a distinguished entry in the virtual table. Consider the following code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }

    // Circle
    public double CalculateArea(double radius, int unused)
    {
        return radius * radius * 3.14159;
    }
}

This would result in:

Method NameArgument(s)Encoding
CalculateAreaCalculate@None
CalculateAreadoubleCalculate@Double
CalculateAreadouble, doubleCalculate@Double@Double
CalculateAreadouble, doubleCalculate@Double@Integer

Notice that the encodings are distinct. Remember that, normally, you need only one value to calculate the areas of a square or a circle. To distinguish their calculations in our code, we passed a second argument to the area of the circle. We named the argument "unused" but you can use any name (one of the differences between C++ and C# is that in the former, you can omit a name; therefore, if this code were written in C++, we would not have to name the argument). When calling the method that takes two argument, you must pass a value for the second argument. Since the method will not use the argument, you can pass any value, as long as it is conform to the type. Here is an example of using the above code:

C#
public class Geometry
{
    // Unknown Shape
    public double CalculateArea()
    {
        return 0D;
    }

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

    // Rectangle
    public double CalculateArea(double length, double height)
    {
        return length * height;
    }

    // Circle
    public double CalculateArea(double radius, int unused)
    {
        return radius * radius * 3.14159;
    }
}

public class Exercise
{
    static int Main()
    {
        var geo = new Geometry();

        System.Console.WriteLine("Geometric Shapes");
        System.Console.WriteLine("Calculation of Areas");
        System.Console.Write("Square:    ");
        System.Console.WriteLine(geo.CalculateArea(26.38));
        System.Console.Write("Rectangle: ");
        System.Console.WriteLine(geo.CalculateArea(39.17, 26.38));
        System.Console.Write("Circle:    ");
        System.Console.WriteLine(geo.CalculateArea(26.38, 0));

        return 0;
    }
}

This would produce:

C#
Geometric Shapes
Calculation of Areas
Square:    695.9044
Rectangle: 1033.3046
Circle:    2186.246303996
Press any key to continue . . .

Method overloading is heavily used in the .NET Framework. Therefore, remember its (two, either-or) rules. Fortunately, they are (very) easy: The methods must use either different numbers of arguments or different types of arguments. When a method is overloaded, when you access it in the Code Editor, the IntelliSense would show a label with 1 of X. The X indicates the number of versions that the method has. Here is an example of a function that has three versions, thus the IntelliSense indicates 1 of 3:

To select one of the versions, you can press the down arrow key or you can start typing the value of the argument until the right version is shown.

An Argument With an Optional Value#

We have learned that if a method takes an argument, when you call that method, you must provide a value for the argument. There is an exception to this rule. If you have a method whose argument is usually given the same value, you can give a default value to that argument. Consider the following code:

C#
public class Exercise
{
    double CalculateNetPrice(double discountRate)
    {
        double origPrice = 125.55;

        return origPrice - (origPrice * discountRate / 100);
    }

    static int Main()
    {
        var exo = new Exercise();
        double finalPrice;
        double discount = 15; // That is 25% = 25

        finalPrice = exo.CalculateNetPrice(discount);

        System.Console.WriteLine("After applying the discount");
        System.Console.Write("Final Price = ");
        System.Console.WriteLine(finalPrice);

        return 0;
    }
}

This would produce:

C#
After applying the discount
Final Price = 106.7175
Press any key to continue . . .

To specify that an argument has a default value, in the parentheses of the method, after the name of the argument, assign the default value to it. Here is an example:

C#
public class Exercise
{
    double CalculateNetPrice(double discountRate = 25)
    {
        double origPrice = 125.55;

        return origPrice - (origPrice * discountRate / 100);
    }
}

When calling the method, you can pass a value for the argument. If you want to use the default value, omit passing the argument. Here is an example:

C#
public class Exercise
{
    double CalculateNetPrice(double discountRate = 25)
    {
        double origPrice = 125.55;

        return origPrice - (origPrice * discountRate / 100);
    }

    static int Main()
    {
        var exo = new Exercise();
        double finalPrice;

        finalPrice = exo.CalculateNetPrice();

        System.Console.WriteLine("After applying the discount");
        System.Console.Write("Final Price = ");
        System.Console.WriteLine(finalPrice);

        return 0;
    }
}

Notice that the parentheses of the method are empty, which means that the argument was not passed. This would produce:

C#
After applying the discount
Final Price = 94.1625
Press any key to continue . . .

In the same way, you can create a method that takes many arguments and some or all of those arguments can have default values. If a method takes more than one argument, you can provide a default argument for each and select which ones would have default values. If you want all arguments to have default values, when defining the method, type each name followed by = and followed by the desired value. Here is an example:

C#
public class Exercise
{
    double CalculateNetPrice(double tax = 5.75,
                             double discount = 25,
                             double origPrice = 245.55)
    {
        double discountValue = origPrice * discount / 100;
        double taxValue = tax / 100;
        double netPrice = origPrice - discountValue + taxValue;

        System.Console.Write("Original Price: $");
        System.Console.WriteLine(origPrice);
        System.Console.Write("Discount Rate: ");
        System.Console.Write(discount);
        System.Console.WriteLine("%");
        System.Console.Write("Tax Amount: $");
        System.Console.WriteLine(tax);

        return netPrice;
    }

    static int Main()
    {
        var exo = new Exercise();
        double finalPrice;

        finalPrice = exo.CalculateNetPrice();

        System.Console.WriteLine("After applying the discount");
        System.Console.Write("Final Price = ");
        System.Console.WriteLine(finalPrice);

        return 0;
    }
}

This would produce:

C#
Original Price: $245.55
Discount Rate: 25%
Tax Amount: $5.75
After applying the discount
Final Price = 184.22
Press any key to continue . . .

If a method takes more than one argument and you would like to provide default values for those parameters, the order of appearance of the arguments is very important.

  • If a method takes two arguments, you can declare it with default values. We already know how to do that. If you want to provide a default value for only one of the arguments, the argument that would have a default value must be the second. When calling such a function, if you supply only one argument, the compiler would assign its value to the first parameter in the list and ignore assigning a value to the second: public class Exercise { double CalculateNetPrice(double taxRate, double discountRate = 25) { double origPrice = 185.95; double discountValue = origPrice * discountRate / 100; double taxValue = taxRate / 100; double netPrice = origPrice - discountValue + taxValue; return netPrice; } static int Main() { double finalPrice; double taxRate = 5.50; // = 5.50% Exercise exo = new Exercise(); finalPrice = exo.CalculateNetPrice(taxRate); System.Console.WriteLine( "After applying a 25% discount and a 5.50% tax rate"); System.Console.Write("Final Price = "); System.Console.WriteLine(finalPrice); return 0; } } Here is an example of running the program: After applying a 25% discount and a 5.50% tax rate Final Price = 139.5175 Press any key to continue . . . If you define the function and assign a default value to the first argument, if you provide only one argument when calling the function, you would receive an error. Consider the following code: public class Exercise { double CalculateNetPrice(double discountRate = 25, double taxRate) { double origPrice = 185.95; double discountValue = origPrice * discountRate / 100; double taxValue = taxRate / 100; double netPrice = origPrice - discountValue + taxValue; return netPrice; } static int Main() { double finalPrice; double taxRate = 5.50; // = 5.50% Exercise exo = new Exercise(); finalPrice = exo.CalculateNetPrice(taxRate); System.Console.WriteLine( "After applying a 25% discount and a 5.50% tax rate"); System.Console.Write("Final Price = "); System.Console.WriteLine(finalPrice); return 0; } } This would produce two errors as: Error 1 Optional parameters must appear after all required parameters C:\Exercises\Bank\Exercise.cs 3 70 Bank
  • If the method receives more than two arguments and you would like only some of those arguments to have default values, the arguments that have default values must be at the end of the list. Regardless of how many arguments would or would not have default values, start the list of arguments with those that would not use default values. Here is an example: public class Exercise { double CalculateNetPrice( double origPrice, double taxRate = 5.75, double discountRate = 25 ) { double discountValue = origPrice * discountRate / 100; double taxValue = taxRate / 100; double netPrice = origPrice - discountValue + taxValue; return netPrice; } } When calling the method, you can provide a value for only the argument(s) that do(es) not have a default value: public class Exercise { double CalculateNetPrice(double origPrice, double taxRate = 5.75, double discountRate = 25) { double discountValue = origPrice * discountRate / 100; double taxValue = taxRate / 100; double netPrice = origPrice - discountValue + taxValue; return netPrice; } static int Main() { double originalPrice = 375.95; double finalPrice; Exercise exo = new Exercise(); finalPrice = exo.CalculateNetPrice( originalPrice ); System.Console.WriteLine( "After applying a 25% discount and a 5.75% tax rate"); System.Console.Write("Final Price = "); System.Console.WriteLine(finalPrice); return 0; } } Here is an example of running the program: After applying a 25% discount and a 5.75% tax rate Final Price = 282.02 Press any key to continue . . . As you can see, the argument(s) that has(have) default value(s) must be last in the list of arguments.

Application: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No

Previous Copyright © 2010 C# Key Next