OneBite.Dev - Coding blog in a bite size

Declare A Function With Return Value In C#

Code snippet for how to Declare A Function With Return Value In C# with sample and detail explanation

In programming, functions become central to organizing, structuring and reusing codes. In C#, declaring a function with a return value is crucial to automate and execute a specific task efficiently. This article will provide a simple introduction on how to declare a function with a return value in C# through an easy-to-understand code example and a thorough step-by-step explanation.

Code snippet: Declaring a function with a return value

using System;

class Program
{
    static void Main()
    {
        int result = Add(5, 10);
        Console.WriteLine(result);
    }

    static int Add(int a, int b)
    {
        return a + b;
    }
}

Code Explanation for Declaring a function with a return value

This code includes code snippets for how to declare a function with a return value in C#. The function name here is Add, which takes in two int parameters, a and b and returns an int. Here’s how it works:

  1. At the beginning of the code, we’re first importing the System namespace which gives us access to Console.WriteLine() method we’ll be using to print the result on the console.

  2. Create a class Program. In C#, all lines of code must be inside a class.

  3. Inside the Program class, create the Main method. This is the entry point of our application where we call our function.

  4. Inside the Main method, we’re calling Add function with two integers as parameters (5 and 10). The Add function then gives back a return value that we store in result variable.

  5. After that, we’re telling our program to print out the result of the Add function with Console.WriteLine(result);

  6. Following that, outside of the Main method but still within the Program class, we declare the Add function.

  7. This function is declared with the static keyword and its return type is int.

  8. The Add function takes two parameters, both of int type. These two values are summed within the function and are given back through the return statement.

Thus, by following these steps, you can successfully declare a function with a return value in C#. Understanding how to correctly return values from functions will greatly enhance your ability to write efficient, reusable, and organized code.

c-sharp