
.NET 1.1+C# Methods (2)
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.
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