CS Function

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:

  • Function name: It is a unique name for calling functions.
  • Return type: The function return value is used to indicate the data type.
  • Body: It is an executable statements block.
  • Access specifier: It is used in the application to specify function accessibility.
  • Parameters: This is a list of arguments we can use during a call to the 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

 

C# Function: using parameter but no return type

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.

 

 

C# Function: using parameter and return type

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