In this article, we will learn about functions in C#.
Function is a block of code that has a signature. Function is used to execute statements specified in the code block. A function consists of the following components:
FunctionName( ) { // function body // return statement } </pre> Access-specifier, parameters and return statement are optional.
Let's see an example in which we have created a function that returns a string value and takes a string parameter.
C# Function: using no parameter and return type
A function that does not return any value specifies void type as a return type. In the following example, a function is created without return type.using System; namespace FunctionExample { class Program { // User defined function without return type public static void Show() // No Parameter { Console.WriteLine("This is non parameterized function"); // No return statement } // Main function, execution entry point of the program static void Main(string[] args) { Show(); // Calling Function } } }
Output:
This is non parameterized function
C# Function: using parameter but no return type
using System; namespace FunctionExample { class Program { // User defined function without return type public static void Show(string message) { Console.WriteLine("Hello " + message); // No return statement } // Main function, execution entry point of the program static void Main(string[] args) { Show("Rahul Kumar"); // Calling Function } } }
Output:
Hello Rahul Kumar
C# Function: using parameter and return type
A function can have zero or any number of parameters to get data.
In the following example, a function is created without parameters.
A function without parameter is also known as non-parameterized function.using System; namespace FunctionExample { class Program { // User defined function public static string Show(string message) { Console.WriteLine("Inside Show Function"); return message; } // Main function, execution entry point of the program static void Main(string[] args) { string message = Show("Rahul Kumar"); Console.WriteLine("Hello " + message); } } }
Output:
Inside Show Function
Hello Rahul Kumar
Task
In the editor below, perform the different tasks as directed.
Create a function name addition which takes two integers as input and returns their sum as output.</p>