C# Functions

Introduction

A function (or method) in C# is a block of code that performs a specific task. Functions help organize code into manageable sections, making it easier to understand, maintain, and reuse. Functions can take input parameters, execute statements, and return a value.

Syntax

Defining a Function

returnType FunctionName(parameterList)
{
    // Function body
    // Code to execute
    return value; // For non-void functions
}

Calling a Function

FunctionName(arguments);

Example: Defining and Calling a Function

Function with Return Value

using System;

namespace FunctionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Call the AddNumbers function and store the result in sum
            int sum = AddNumbers(5, 3);
            Console.WriteLine("The sum is: " + sum);
        }

        // Function that returns the sum of two numbers
        static int AddNumbers(int a, int b)
        {
            return a + b; // Return the sum of a and b
        }
    }
}

Output

The sum is: 8

Function without Return Value (void)

using System;

namespace FunctionVoidExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Call the PrintMessage function
            PrintMessage();
        }

        // Function that prints a message
        static void PrintMessage()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Output

Hello, World!

Parameters

Functions can take parameters, which are variables that you pass into the function. Parameters allow you to pass data into functions so that they can perform operations on that data.

Example: Function with Parameters

using System;

namespace FunctionParametersExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Call the Greet function with different names
            Greet("Alice");
            Greet("Bob");
        }

        // Function that takes a string parameter and prints a greeting
        static void Greet(string name)
        {
            Console.WriteLine("Hello, " + name + "!");
        }
    }
}

Output

Hello, Alice!
Hello, Bob!

Returning Values

Functions can return values to the caller using the return statement. The return type of the function must match the type of the value returned.

Example: Function Returning a Value

using System;

namespace ReturnFunctionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Call the Square function and store the result
            int result = Square(4);
            Console.WriteLine("The square of 4 is: " + result);
        }

        // Function that returns the square of a number
        static int Square(int number)
        {
            return number * number;
        }
    }
}

Output

The square of 4 is: 16

Overloading Functions

Function overloading allows you to define multiple functions with the same name but different parameter lists. The correct function is chosen based on the number and type of arguments passed.

Example: Overloaded Functions

using System;

namespace OverloadedFunctionsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Call the overloaded Add functions
            Console.WriteLine("Sum of 5 and 3: " + Add(5, 3));
            Console.WriteLine("Sum of 5, 3, and 2: " + Add(5, 3, 2));
        }

        // Function to add two integers
        static int Add(int a, int b)
        {
            return a + b;
        }

        // Overloaded function to add three integers
        static int Add(int a, int b, int c)
        {
            return a + b + c;
        }
    }
}

Output

Sum of 5 and 3: 8
Sum of 5, 3, and 2: 10

Recursion

A function can call itself; this is known as recursion. Recursive functions are useful for tasks that can be broken down into smaller, repetitive tasks.

Example: Recursive Function

using System;

namespace RecursiveFunctionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Call the Factorial function and print the result
            int number = 5;
            int result = Factorial(number);
            Console.WriteLine("The factorial of " + number + " is: " + result);
        }

        // Function to calculate the factorial of a number
        static int Factorial(int n)
        {
            if (n == 1)
            {
                return 1;
            }
            else
            {
                return n * Factorial(n - 1);
            }
        }
    }
}

Output

The factorial of 5 is: 120

Conclusion

Functions in C# are essential for organizing code into manageable sections. They allow you to perform specific tasks, take parameters, return values, and even call themselves recursively. By understanding and using functions, you can write more modular, readable, and maintainable code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top