BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Methods

The forty-fourth part of the C# Fundamentals tutorial starts to bring together the information in the earlier articles to allow the construction of a fully working program. In this instalment, the creation and calling of custom methods is considered.

What is a Method?

In the first article in the C# fundamentals tutorial I introduced the concept of a method. A method is a discrete piece of code that can be called by other functions. When a called, control of the program is passed to the method, which performs its activities before returning control back to the command following the calling statement. Often methods call other methods in a nested arrangement.

The use of methods provides several benefits. A key advantage is that code that would otherwise be repeated can be held in a single location. If the code for a particular function exists in one subroutine, modifications and bug fixes are much simpler than if the code has been duplicated. A second benefit is that when a method is given a descriptive name, it can make your source code easier to understand. This helps create self-documenting code, which requires fewer comments due to its simplicity.

Methods are always linked to a class or structure. However, the object-oriented concepts of classes are beyond the scope of a beginner's tutorial. As with previous articles, the examples described will be limited to a single-class program.

Creating a Method

In this section we will create a simple method that obtains the current date and time. The date part will be outputted to the console. Although the functionality is simple, it serves as a good demonstration of the structure of a method and illustrates how the code could be modified centrally should, for example, the formatting of all dates need to be changed throughout a large program.

Naming a Method

Methods can be named using the same rules as variables. Upper and lower case letters, numeric digits and the underscore (_) character are allowed. Although any combination of these characters is permissible, methods should be given descriptive names that indicate the action that they perform. A common standard is to use Pascal Case for the method name, meaning that the first letter of the method name is capitalised and the remaining text is lower case. Where several words are joined together, each word begins with a capital letter.

Using these conventions, good names for methods could include:

  • Delete
  • DeleteFile
  • ConnectToDatabase
  • OutputFormattedDate

Creating a Method

The simplest type of method is one that performs a task without requiring any parameters and without returning any information. This is the type of method that we will create in this article. More complex methods will be investigated in later instalments of the tutorial.

Declaring a method is similar to defining a variable. The type of the return value of the method is followed by the method name. If there is no return value, the type is set to void. As we are using no parameters, an empty pair of parentheses () is appended. The code to declare our example method is as follows:

void OutputFormattedDate()

NB: To use this example, create a console application and add the code within the braces of the class but outside of the 'Main' method. The full example can be found at the end of this article.

Adding Code

Once the method is declared, it needs a code block. Like all code blocks, the series of commands is surrounded by brace characters, {}. The following example adds the code to output the formatted date to the console.

void OutputFormattedDate()
{
    DateTime theDate = DateTime.Now;
    Console.WriteLine(theDate.ToString("dd/MM/yyyy"));
}

Returning From a Method on Completion

The example method above simply determines the current date and outputs it. After the Console.WriteLine command the method has no further code to execute so control returns to the point where the method was originally called. However, it is possible to instruct the program to return from a method at any point by adding a return statement. The following example shows this by returning without outputting the date if it is Christmas day.

void OutputFormattedDate()
{
    DateTime theDate = DateTime.Now;
    if (theDate.Day == 25 && theDate.Month == 12)
    {
        return;
    }
    Console.WriteLine(theDate.ToString("dd/MM/yyyy"));
}

The return command may be used several times within a method to exit at different points according to your requirements. However, the number of return points should be kept to a minimum in order to keep the code readable. Ideally you should only have one return statement or the method should exit naturally when control reaches the closing brace character.

Calling a Method

Now that the method is complete it can be called. As with other methods examined through in this tutorial, it belongs to a class. If you are using a standard console application, this class will be called Program and will contain a Main method as well as OutputFormattedDate. To use the new method, you must first create a new Program object and call its OutputFormattedDate function. This can be controlled within the Main method, making the final code as follows:

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        p.OutputFormattedDate();
    }


    void OutputFormattedDate()
    {
        DateTime theDate = DateTime.Now;
        Console.WriteLine(theDate.ToString("dd/MM/yyyy"));
    }
}

/* OUTPUT

19/07/2007

*/
19 July 2007