C# Function to Double an Integer Using Reference Parameters

In this C# program, we define a function named "Double" that calculates the double of an integer and modifies the passed argument using reference parameters. The function will be a "void" function, meaning it does not return any value but directly modifies the input parameter. The reference parameters allow the original value to be modified outside the function. In the example provided, calling Double(ref x) will modify the value of x to 10. This demonstrates how to work with reference parameters in C#.



Group

Functions in C#

Objective

1. Define a function named "Double" that accepts an integer parameter by reference using the `ref` keyword.
2. Inside the function, multiply the input integer by 2.
3. As the function is a "void" function, it does not return anything but modifies the value of the parameter directly.
4. In the Main method, declare an integer variable and pass it to the "Double" function using the `ref` keyword.
5. Display the result using Console.Write.

Write a C# function named "Double" to calculate the double of an integer number, and modify the data passed as an argument. It must be a "void" function and you must use "reference parameters". For example, x = 5; Double(ref x); Console.Write(x); would display 10.

public static void Main()
{
    int x = 5;
    Double(ref x);  // Pass x by reference to the Double function
    Console.Write(x);  // This should print 10
}

Example C# Exercise

 Copy C# Code
using System;

class Program
{
    // Main method where the program execution begins
    public static void Main()
    {
        // Declare an integer variable x and initialize it with 5
        int x = 5;
        
        // Call the Double function with x passed by reference
        Double(ref x);  // This will modify the value of x to 10
        
        // Display the modified value of x
        Console.Write(x);  // This should print 10
    }

    // Function to double the value of the input integer using reference parameter
    public static void Double(ref int number)
    {
        // Multiply the input number by 2 and update the value directly
        number *= 2;  // This will modify the value of number
    }
}

 Output

10

Share this C# Exercise

More C# Practice Exercises of Functions in C#

Explore our set of C# Practice Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.