BlackWasp
C# Programming
.NET 1.1

C# Functional Methods

The forty-fifth part of the C# Fundamentals tutorial expands upon the creation of methods described in the previous instalment.  In this article, the creation of methods that return a value and that can accept parameters is considered.

Functional Methods

In the previous article describing C# methods, simple methods were created in order to centralise standard tasks, increasing the readability and maintainability of the code.  However, these methods worked in isolation only as there was no facility to pass information to the function using parameters and no value returned on completion of the call.  Although this is useful, most of the methods that you create will require the use of parameters, return values or both.

Creating a Method that Returns a Value

In the previous article, we created a method that obtained the current date and time and outputted it to the console in a desired format.  In this article, we will create a similar method that returns the date and time rather than outputting it.  Methods can be created that use any value type or reference type for the return value.  In this case, the formatted date and time will be returned as a string.

A method with a return value is declared in a similar manner to a variable.  The variable type is indicated first, followed by the name of the method and a pair of parentheses ().  The code for the method is then appended within a code block.  The code to declare our empty example method is therefore as follows:

string GetFormattedDate()
{

}

To return a value to the calling procedure, the return command is used.  The return command is followed by the value or object that is to be passed back, as follows:

string GetFormattedDate()
{
    DateTime theDate = DateTime.Now;
    return theDate.ToString("dd/MM/yyyy");
}

Now that the method has been created, it can be called in the same manner as any other method.  If you are using a standard console application, the default class will be called Program and will now contain a Main method as well as GetFormattedDate.  To use the new method, you must first create a new Program object and call its GetFormattedDate function, assigning the result to a variable.  This can be controlled within the Main method making the final code as follows:

static void Main(string[] args)
{
    Program p = new Program();
    string outputDate = p.GetFormattedDate();

    Console.WriteLine(outputDate);              // Outputs "26/07/2007"
}


string GetFormattedDate()
{
    DateTime theDate = DateTime.Now;
    return theDate.ToString("dd/MM/yyyy");
}

Adding Parameters

So far, all of the methods created in the tutorial can only perform a single task and their operation cannot be configured.  By adding parameters to a method, information can be passed from the calling function to control the processing.

Any number of parameters may be added to the definition of a method by declaring each parameter within the method's parentheses, separated by commas.  Each parameter must have a defined data type that is declared using the same syntax as when creating an uninitialised variable.

The parameters of a method behave differently according to the type of data they convey.  For parameters that are declared as value types, a copy of the parameter's information is passed to the method.  This means that if a variable is used as a parameter and the value is modified within the method, the value of the variable in the calling method is unaffected.  However, if a parameter is of a reference type and receives an instance of a class, a copy of the reference to the object is passed to the method.  Any change to the parameter variable that occurs within the method will therefore also be seen outside of the method.  This is because both references are pointing to the same data in the computer's memory.

For this example, we will create a method that accepts two parameters that define the width and height of a rectangle.  The two values will be multiplied to obtain the rectangle's area and the resultant value returned.  Firstly, the method is defined with the return value and the two parameters specified.  Note that the parameters are defined in lower camel case where the initial letter of each word in a name is capitalised, with the exception of the first word that is entirely lower case.  This is a useful convention for variable naming though not strictly necessary.

int GetArea(int rectHeight, int rectWidth)
{
    return rectHeight * rectWidth;
}

The method may now be called with the parameter values specified.  The following example demonstrates this:

static void Main(string[] args)
{
    Program p = new Program();
    int area = p.GetArea(10, 5);                // Outputs "50"

    Console.WriteLine(area);
}


int GetArea(int rectHeight, int rectWidth)
{
    return rectHeight * rectWidth;
}

Static Methods

In the example above, a new object of the class Program was created so that the method declared could be executed.  You may have noticed that the Main method was declared differently to the OutputFormattedDate method with the addition of the static prefix.  This prefix declares the method as a static method, meaning that no object needs to be created before the method is called.  By prefixing the new method with the same static keyword, we can remove the requirement to create a Program object.

static void Main(string[] args)
{
    int area = GetArea(10, 5);                  // Outputs "50"

    Console.WriteLine(area);
}


static int GetArea(int rectHeight, int rectWidth)
{
    return rectHeight * rectWidth;
}
Link to this Page26 July 2007
RSS RSS Feed
67 users on-line