OneBite.Dev - Coding blog in a bite size

Call A Function With Parameter In C#

Code snippet for how to Call A Function With Parameter In C# with sample and detail explanation

In C#, calling a function with parameter plays a crucial role in day-to-day coding routine. In this article, we will illustrate how to call a function with parameter in C# along with a practical example and step by step explanation.

Code snippet for Function With Parameter In C#

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number:");
        int num = Convert.ToInt32(Console.ReadLine());
        PrintNumber(num);
    }

    static void PrintNumber(int number)
    {
        Console.WriteLine("The number you entered is: " + number);
    }
}

Code Explanation for Function With Parameter In C#

In the above code, we have defined a function PrintNumber(int number) that takes an integer as a parameter. Note that the parameter ‘number’ acts just like a local variable inside the PrintNumber function.

Let’s break down just how this code works:

  1. The program starts from Main(string[] args).
  2. As soon as the program starts, it prompts the user to enter a number with a line Console.WriteLine("Enter a number:").
  3. Then, it reads the input number using Console.ReadLine() which is then converted to integer using Convert.ToInt32(). The entered number is stored in the local variable ‘num’.
  4. The function PrintNumber(num) is then called with ‘num’ as its argument.
  5. When the function PrintNumber(int number) is called, it takes the integer number entered by user (‘num’) and then prints it on the console with the line Console.WriteLine("The number you entered is: " + number).

In this way, we can create a function with parameters in C# and call it from the Main function or elsewhere in our program. This allows us to reuse our code and have a cleaner, more organized program structure.

c-sharp