Functions in C#

In C#, if you need to perform a specific task repeatedly in your code, then instead of writing same code for it it again and again, you can simply create a function that can perform the task. Then, whenever you want to do that specific task, you can simply call the function.

Every function in C# has two parts.

    1. Function Definition which includes code to be executed
    2. Function call

Function Definition

A function is first need to be defined before it can be called. Have a look at the following example to see how function can be defined and called.

using System;

namespace CSharpTutorials {
    class Tutorial {
            static void Main(string[] args)  {
				int result = performAddition(5, 10);
				Console.WriteLine("The result of addition is: " + result);
				Console.ReadKey();
            }
            public static int performAddition(int a, int b)   {
                return a + b;
            }
    }
}

Download the code

In the above code, a function named performAddition has been defined. A function definition consists of following parts.

Access modifier

This defines the level at which a function can be accessed by the other function and classes. The peformAddition function has a public access modifier.

The return type

This is the value that a function returns. It can be void as well which means nothing will be returned. The function defined in above code returns integer type value.

Function name

After the return type, comes the function name which can be anything and should follow identifier naming conventions.

Function Parameters

The last part of function definition is the function parameters. Function parameters are passed via arguments in the function call. They are basically used to pass some values to the function on which function can take action. In the performAddition function, integer ‘a’ and ‘b’ have been passed as parameter to the function.

Function call

You have to call function at the location in your code where you want to execute the functionality performed by the function.

A function is called by calling its name and by passing the required arguments to the function parameters if any. In above example, the performAddition function has been called inside the main function. Since the performAddition method takes two integer values, 5 and 10 has been passed to in the parenthesis that follow function name.

This function performs the addition of two integers and returns the value which has been printed using Console.WriteLine function on the console screen.

<<< Arrays in C#CSharp Class, Object >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .