Introduction to Functions in C#

A stylized circuit board saying "hello world"

alengo/Getty Images

In C#, a function is a way of packaging code that does something and then returns the value. Unlike in C, C++ and some other languages, functions do not exist by themselves. They are part of an object-oriented approach to programming.

A program to manage spreadsheets might include a sum() function as part of an object, for example.

In C#, a function can be called a member function—it is a member of a class—but that terminology is left over from C++. The usual name for it is a method.

The Instance Method

There are two types of methods: instance method and static method. This introduction covers the instance method.

The example below defines a simple class and calls it Test. This example is a simple console program, so this is allowed. Usually, the first class defined in the C# file must be the form class.

It's possible to have an empty class like this class Test { }, but it isn't useful. Although it looks empty, it—like all C# classes—inherits from the Object that contains it and includes a default constructor in the main program.

var t = new Test();

This code works, but it won't do anything when run except create an instance t of the empty test class. The code below adds a function, a method that outputs 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() ;
}
}
}

This code example includes Console.ReadKey(), so when it runs, it displays the console window and awaits a key entry such as Enter, Space or Return (not the shift, Alt or Ctrl keys). Without it, it would open the console Window, output "Hello" and then close all in the blink of an eye.

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

If you remove the word public and try to compile the code, it fails 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 and recompile, you get the same compile error. Just change it back to "public."

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

Typical Function Definition 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

The code for the definition of another function, MyAge(), is:

public int MyAge()
{
return 53;
}

Add that right after the SayHello() method in the first example 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. A more useful example is the spreadsheet Sum function with 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 and then has the relevant parts of the array values added.

Format
mla apa chicago
Your Citation
Bolton, David. "Introduction to Functions in C#." ThoughtCo, Feb. 16, 2021, thoughtco.com/introduction-to-functions-in-c-958367. Bolton, David. (2021, February 16). Introduction to Functions in C#. Retrieved from https://www.thoughtco.com/introduction-to-functions-in-c-958367 Bolton, David. "Introduction to Functions in C#." ThoughtCo. https://www.thoughtco.com/introduction-to-functions-in-c-958367 (accessed March 28, 2024).