Tuesday, January 1, 2013

5.2. Basic concepts about functions


In C#, as in C and other languages ​​derived from it, all the "parts of a program" are functions, including the body of the program, which is always called "Main". In fact, the basic way of defining a function is indicating its name followed by empty parentheses, as we did with "Main", and preceded by certain keywords, like "public static void", whose meaning we will see soon. After that, and delimited with curly braces, we indicate the steps that this "piece of program" must take.

For example, we could create a function called "greet", to display several messages on the screen:

public static void Greet()
{
  Console.WriteLine("Welcome to the");
  Console.WriteLine("example program.");
  Console.WriteLine("I hope you are fine.");
}

Now from within the body of our program, we could "call" this function:

public static void Main()
{
  Greet();
  …
}

This way, we make our main program easier to read.

An important detail: both the usual function "Main" and the new "greet" would be part of our "class", so the complete source would look like this:

/*---------------------------*/
/*  C# Example #47:          */
/*  example47.cs             */
/*                           */
/*  Function "Greet"         */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example47
{

  public static void Greet()
  {
    Console.WriteLine("Welcome to the");
    Console.WriteLine("example program.");
    Console.WriteLine("I hope you are fine.");
  }

  public static void Main()
  {
    Greet();
    Console.WriteLine("Finished.");
  }
 
}

As a more detailed example, the main part of a small database manager like the ones we created in the previous chapter, could look like:

readDataFromFile();
do {
  displayMainMenu();
  getOptionFromUser();
  switch( option ) {
    case 1: searchData(); break;
    case 2: modifyData(); break;
    case 3: addData(); break;
    …


Suggested exercises:
·       (5.2.1) Create a function named "ClearScreen", to clear the screen by drawing 25 blank lines. It should not return any value. Create a "Main" to test it.
·       (5.2.2) Create a function named "Draw3x3rectangle", to display three rows, with three asterisks each. Create a "Main" to test it.
·       (5.2.3) Split into functions any of the databases created in the previous topic (such as the one to store people or files), so that the "Main" function is shorter and more readable. (Hint: the variables which are shared by several functions will have to be out of those functions, and preceded by the word "static").

No comments:

Post a Comment