1. Technology

Introduction to Functions in C#

By

In the previous tutorial, we looked at an object oriented approach to programming and we'll return to that again in the future but in this tutorial I'll be covering functions.

  • Download a zip file with the complete source code for this tutorial.

A function is a way of packaging up code that does something, say like calculating the total of an array of ints and then returns the value. However unlike C/C++ and some other languages, functions do not exist by themselves. They are part of an object- defined in a class or sometimes in a struct.

If we were for example creating a program to manage spreadsheets (i.e. something like Excel), we might include a sum() function as part of this object.

In C#, a function can be called a member function (after all it's a function that is a member of the class) but that's a hangover from C++ and the usual name for it is a method.

There are two types of method: instance method and static method. We'll look at static methods in the next tutorial.

Let's define a simple class and call it test. I've created it it before the class Program. Note, in this example it's just a simple console program so this is allowed. In a Winforms application, the first class defined in the C# file must be the form class. The form designer gets upset if you don't do this.

It's possible to have a completely empty class like this class Test { } but it's about as much use as a bridge made of chocolate in the Sahara desert. Actually, although it looks empty, it (like all C# classes) inherits from Object and includes a default constructor so in the main program .

var t = new Test();

That will work. It still won't do anything when run except create an instance t of the empty test class. So let's add our first function, a method that will output the word Hello.

using System;
namespace funcex1
{
    class Test
    {
        public void SayHello()
        {
            Console.WriteLine("Hello") ;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var t = new Test() ;
            t.SayHello() ;
            Console.ReadKey() ;
        }
    }
}

I've added Console.ReadKey() so when it runs, it displays the console window and waits until you hit a key such as Enter, Space or Return (not the shift, Alt or Ctrl keys). Without it, it would open the console Window, output Hello then close it all in the blink of an eye.

The function SayHello is about as simple as you can have a function. It's a public function which means the function is visible from outside of the class.

Try removing the word public and try and compile it now. It will fail with a compilation error 'funcex1.test.SayHello()' is inaccessible due to its protection level. If you add the word private where the word public was (i.e. before void) and recompile, you'll get the same compile error. Just change it back to public.

The word void in the function means that our function does not return any values.

More formally a function is defined with these characteristics:

  • Access level - public, private plus some others
  • Return value> - void or any type such as int
  • Method Name - SayHello
  • Any method parameters - none for now- these are defined in the brackets () after the method name

Let's define another function MyAge().

public int MyAge()
{
  return 53;
}

Add that straight after the SayHello() method and add these two lines before Console.ReadKey().

var age = t.MyAge();
Console.WriteLine("David is {0} years old",age);

Running the program now outputs this:

Hello
David is 53 years old,

The var age = t.MyAge(); call to the method returned the value 53. It's not the most useful function so let's finish this tutorial with something a bit more useful. This is our Excel like Sum function. We'll pass in an array of ints, the start index and the number of values to sum.

This is the function:

public float Sum(int[] values, int startindex, int endindex)
{
    var total = 0;
    for (var index=startindex; index<=endindex; index++)
    {
        total += values[index];
    }
    return total;
}

Here are three use cases. This is the code to add in Main() and call to test the Sum function.

var values = new int[10] {1, 2, 3, 4, 5, 6, 7, 8, 9,10};
Console.WriteLine(t.Sum(values,0,2)); // Should be 6
Console.WriteLine(t.Sum(values,0,9)); // should be 55
Console.WriteLine(t.Sum(values,9,9)); // should be 10 as 9th value is 10

The For loop adds up the values in the range startindex to endindex so for startindex =0 and endindex=2 this is the sum of 1 + 2 + 3 = 6. Whereas for 9,9, it just adds the one values[9] = 10.

Within the function the local variable total is initialized to 0 then has the relevant parts of the array values added.

This concludes this introduction tutorial to functions. In the next one we'll see more advanced uses.

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Functions in C# - Introduction and Tutorial

©2014 About.com. All rights reserved.