Defining and Using Functions

Starting with the basics, you look at simple functions that don ’ t exchange any data with code that calls them, and then look at more advanced function usage. The following example demonstrate things easily :

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Write()
        {
            Console.WriteLine("Text output from function.");
        }
        static void Main(string[] args)
        {
            Write();
            Console.ReadKey();
        }
    }
}

How It Works :
The following four lines of your code define a function called Write() :

static void Write()
{
  Console.WriteLine("Text output from function.");
}

The code contained here simply outputs some text to the console window, but this behavior isn ¡¯ t that important at the moment, because the focus here is on the mechanisms behind function definition and use. The function definition here consists of the following:
 
1) Two keywords: static and void
2) A function name followed by parentheses, Write()
3) A block of code to execute enclosed in curly braces
 
The code that defines the Write() function looks very similar to some of the other code in your application:
static void Main(string[] args)
{
………
}

 
This is because all the code you have written so far (apart from type definitions) has been part of a function. This function, Main() , is the entry point function for a console application. When a C# application is executed, the entry point function it contains is called; and when this function is
completed, the application terminates. All C# executable code must have an entry point.
 
The only difference between the Main() function and your Write() function (apart from the lines of code they contain) is that there is some code inside the parentheses after the function name Main . This is how you specify parameters, which you see in more detail shortly.
 
As mentioned earlier, both Main() and Write() are defined using the static and void keywords. The static keyword relates to object – oriented concepts.
 
void , in contrast, is much simpler to explain. It ’ s used to indicate that the function does not return a value. Later in next tutorials, you see the code that you need to use when a function has a return value. Moving on, the code that calls your function is as follows:
Write();
You simply type the name of the function followed by empty parentheses. When program execution reaches this point, the code in the Write() function runs.