C# Function
A function represents a block of code that has its specific signature. Operating functions includes three operations:
- Function declaration
- Function definition
- Function calling
Syntax:
<access-modifier><return-type><function-name> (<parameter 1>,<parameter 2>…..) { //body statement1 //statement 2 //statement 3 //statement n //return statement }Writing access modifier and parameters is optional which means a function may or may not accept any parameters. The declaration of any function includes following components:
- Function name: it is a unique name which represents the function. This name is called when you call the function.
- Return Type: this is the type which the function returns. It may or may not be void.
- List of parameters: this is the list of parameters which function accepts. A function may or may not accept any parameter.
- Access modifier: this defines the level of accessibility of the function in the application
C# Function Example: without parameter and without return type
using System; public class FunctionExample1 { void display() { Console.WriteLine("inside display function"); } public static void Main (string[] args) { FunctionExample f=new FunctionExample(); f.display(); } }Output inside display function
C# function Example: passing parameters into the function
using System; public class FunctionExample2 { void display(int num) { for(int i=1;i<=10;i++) { Console.WriteLine(num+ " X "+i+ " = "+num*i); } } public static void Main (string[] args) { FunctionExample2 f=new FunctionExample2(); f.display(5); } }Output
5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25 5 X 6 = 30 5 X 7 = 35 5 X 8 = 40 5 X 9 = 45 5 X 10 = 50A function can accept any number of parameters. The function which doesn’t accept any parameter is called non-parameterized function.
C# Function Example: returning value from a function and passing parameters.
using System; public class function_example3 { public string display (string message) { message+=" and this is returned from display function"; return message; } public static void Main(string[] args) { function_example3 p1=new function_example3(); string m=p1.display("this is passed from main"); Console.WriteLine(m); } }Output this is passed from main and this is returned from display function Actual and formal parameters: When you call the function then the variables passed in the function call are called actual arguments or actual parameters. In the function definition, each actual parameter is assigned to a corresponding formal parameter that are mentioned in the function signature.