C# Functions / Methods Tutorial With Code Examples

This Tutorial Explains What Are Functions in C# Programming With Simple Examples. You Will Also Learn The Basic Differences Between Functions And Methods:

We explored all about Loops in C# along with its Types and Examples in our previous tutorial.

In this tutorial, we will be focusing on Functions in C# with simple examples for your easy understanding.

=> FREE C# Training Tutorials For All

C# Functions

Introduction To Functions In C#

In C# a function is defined as a technique of wrapping code to perform a certain task and then return a value. It is quite different than its predecessor programming languages like C or C++. Here the functions do not exist alone. Functions are a part of the OOPs approach.

The function is a member of the class. It is quite the same as a method and sometimes both the terms are used interchangeably. But there are few basic differences between methods and functions.

Difference Between Method And Functions

Although both are similar in many senses and languages. The basic difference between Methods and Functions is that the method comes with a void as return type whereas function has a return type.

If you look into the differences without selecting any particular programming language then the Function can be defined as a piece of code that has a name and arguments for operations mentioned inside the parenthesis. All the argument of a function is explicit by nature.

Now, on the other hand, the method can be seen as a function that acts as an object. It is a blueprint of a class instance. The method always has implicit arguments.

In this tutorial, we will be using the terms Methods and Functions interchangeably for the sake of convenience.

Functions In C#

A function allows the programmers to enclose a piece of code and then call that part of the code from another part of the program. It is quite useful when you need to run the same code from different places.

In C#, functions have the following syntax:

<Access Specifiers> <return type> <name of the function>(< function parameters>)
{
               <function code>
return;
}

As we discussed in our previous tutorials, Access specifies, Parameters and return types are optional. Let’s create functions with different options.

A Function With A Parameter But No Return Type

Let’s create a function by providing some parameters without returning anything.

    
   class Program  
      {  
          // function without any return type declaration  
         public void square(int nmbr)  
         {  
             int sq = nmbr * nmbr;
             Console.WriteLine("Square of the given number is  " + sq);  
            
             // Don’t provide any return statement  
          }  
         
          public static void Main(string[] args)  
         {  
            Program pr = new Program(); // Creating a class Object  
            pr.square( 2); //calling the method
         }  
    }
}

In the program above, we created a function “square” by providing an integer parameter i.e. “nmbr”. Then inside the parenthesis, we have defined the code snippet without providing any return type to the function. In the end, we created a class object and called the “square” function by passing an integer value as an argument.

Output

Square of the given number is 4

Let’s have a look at another example, to clear the things up.

A Function With Both Parameter And A Return Type

Let’s make some changes to the above example and add a return type.

    class Program  
    {  
         // function with integer return type declaration  
        public int square(int nmbr)  
        {  
            int sq = nmbr * nmbr;
            // Lets provide a return statement  
            return sq;
        }  
         
        public static void Main(string[] args)  
        {  
            Program pr = new Program(); // Creating a class Object  
            int rslt = pr.square( 2); //Calling the method and assigning the value to an integer type
            Console.WriteLine("Square of the given number is  "+ rslt); //Printing the result
        }  
    }
}

In the above program, we created a function “square” by providing an integer parameter i.e. “nmbr” and a return type integer. Then inside the parenthesis, we have defined the code snippet followed by a return statement.

Inside the main function, we created a class object and called the “square” function by passing an integer value as an argument. As there is a return type associated, we then stored the function in an integer variable. In the end, we printed the result.

Output

Square of the given number is 4

C# Call By Value

In C# programming language, when we call a function, then it takes a parameter from the main function using the class object. Then the class object inside the main function will copy the function to parameter values. When we use call by value, even if some changes occur within the method that change will not be transferred to the original variable.

Example:

    
   class Program  
   {  
        public void square(int nmbr)  
        {  
           int nmbr = nmbr * nmbr;
           // Lets provide a return statement  
           Console.WriteLine("Square of the given number is  " + nmbr);   
          }  
         
         public static void Main(string[] args)  
         {  
            int nmbr = 2; // Value assigned before calling function
            Program pr = new Program(); // Creating a class Object  
         
            pr.square( nmbr); //calling the method and assigning the defined integer
            Console.WriteLine("The given number is  " + nmbr); //printing the value        
  
         }  
    }
}

So, if we execute the above program we will find the following output:

Square of the given number is 4
The given number is 2

Explanation

In the above example, we defined an integer variable “nmbr” with a value of 2. Then we called the square function by passing the variable as an argument. Hence, the variable that we passed changed into a multiplication of itself (due to operation of the function) and printed the result.

In the main function at the end, we print the variable that we defined earlier. As we can see, there has been no change in the variable value of the function (where it is defined) but it did change when we passed it as an argument for another function.

As we discussed earlier when we call by value any change that will occur to the variable in a method will not be transferred to the original variable. Hence, when we performed the print operation on the variable, it still gives us the previously defined output.

C# Call By Reference

C# offers a “ref” keyword for passing an argument as a reference type for a function. Unlike call by the value, it doesn’t pass the variable to the function after creating a copy of the variable.

It passes the reference of the original value to the function, hence any change that occurs in the referenced value is permanent and is reflected in the original value as well.

Let’s use the same example as earlier but instead of using call by the value we will be using call by reference:

   class Program  
  {  
        public void square(int nmbr)  
        {  
            int nmbr = nmbr * nmbr;
           // Lets provide a return statement  
           Console.WriteLine("Square of the given number is  " + nmbr);   
         }  
         
        public static void Main(string[] args)  
        {  
           int nmbr = 2; // Value assigned before calling function
           Program pr = new Program(); // Creating a class Object  
         
           pr.square( ref  nmbr); //calling by reference using ref keyword
           Console.WriteLine("The given number is  " + nmbr); //printing the value    
      
        }  
    }
}

So, if we execute the program we will find the following output:

Square of the given number is 4
The given number is 4

Explanation

In the above example, we defined an integer variable “nmbr” with a value of 2. Then we called the square function by passing the variable as an argument. So, the variable that we passed changed into a multiplication of itself (due to operation inside the function) and printed the result i.e. 4.

In the main function at the end, we print the variable that we defined earlier. As we can see that there have been changes in the variable value in the function where it was referenced and operated on. As the function performed the operation and variable value changed to 4, the same is reflected in console output.

As we discussed earlier when we call by reference any change that will occur to the variable in a method will be transferred to the original variable. Hence, when we performed the print operation on the variable, it will print the current output i.e. 4.

Conclusion

In this tutorial, we learned about functions in C# programming. The technique to wrap the code is called the function.

In programming languages like C and C++, the function is defined as a code snippet with a name and arguments to perform the operation described inside the parenthesis.

We also learned the basic difference between functions and methods and looked into a few examples to explain the usage of parameters and return types.

=> Check Out The In-Depth C# Training Tutorials Here