Functions in C#

Functions in C#

Functions are used when we need to execute a code more than one and sometimes we separate the part of the code to improve the readability of the code. As C# is an object oriented language so the code is based on classes and classes use functions as methods or functionalities so in this post we learn about both of class functions independent functions and built in function so there are three types of functions in C#.

  • Built-in functions.
  • Class Functions.
  • Independent user defined Functions.

Built-in functions:

The most important example of built-in functions is the main function and in C# the program starts execution from the main function and without it, a code does not run. Rather then main function every code library has a collection of functions like a string library have a length (), compare () and math have abs(), sin () etc.

User Defined Functions:

These functions are defined by the user according to his need like if a user needs a code again and again, which will add two numbers, then we simply create a function which takes two variables and returns their sum.

There are also two types of functions, some are used independently and some are bound to some C# class. The difference in these functions is just in their calling, a function which is bound in class will only be called using its class name. And the independent functions are able to be called anywhere in the program.


access_specifier  return_type  function_name (parameters)

{   \body….       }

Access Specifier: this defines the visibility of the function private, public or protected.

Return Type: this defines the return type of the function that if this function returns some value what’s its type like int, char, bool etc.

Function Name: it’s any name you set for function.

Parameters: they are the values that you pass into a function for execution.

function syntax
Function syntax

The below examples will explain.

  • Function signature or declaration
  • Function definition
  • Function calling.


Recursive Functions:

These functions call themselves and use for recursion.

A complete Example of function in C#:

Demo Class

Main Class