Function is a code block with a signature. Function is used to run the code block statements.
The following elements are part of a function:
FunctionName()
{
// function body
// return statement
}
Access-specificator, return-statement and parameters are optional.
Let's see an example of a function in which we have created the value string that takes a parameter.
A function not returning any value indicates a return type of void
.
Example:
using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show() // No Parameter
{
Console.WriteLine("This function is not parameterised");
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show(); // Calling Function
}
}
}
Output:
This function is not parameterised
Example:
using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show(string message)
{
Console.WriteLine("Hello! " + message);
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show("Uttarakhand Academe"); // Calling Function
}
}
}
Output:
Hello! Uttarakhand Academe
A function can have null or any number of data parameters. A function without parameters is generated in the following example. A parameter-free function is also known as the function non-parameterised.
Example:
using System;
namespace FunctionExample
{
class Program
{
// User defined function
public string Show(string txtmessage)
{
Console.WriteLine("Show Function");
return txtmessage;
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program();
string message = program.Show("Uttarakhand Academe");
Console.WriteLine("Hello! " + message);
}
}
}
Output:
Show Function
Hello! Uttarakhand Academe