Using a control parameter

I myself study C # from a book and will be grateful for the help. I want to create a simple console program so that the user can enter a number that should be doubled. It says that the variable resultin the main method is not assigned, however, what am I doing wrong?

using System;
class Program
{

    private static void Double(ref int num, ref int result)
    {
        result = num * 2;

    }

    private static int readNumber(string question)
    {
        Console.Write(question);
        string ans = Console.ReadLine();
        int number = int.Parse(ans);
        return number;
    }

    public static void Main()
    {
        int num, result;
        num = readNumber("Enter an integer to be doubled: ");
        Double(ref num, ref result);
        Console.WriteLine("The double of {0} is {1}", num, result);
        Console.WriteLine("Press enter to exit...");
        Console.ReadLine();
    }
}
+4
source share
2 answers

The compiler yells at you because it wants to force you to initialize the variables before passing them to the method call.

Value:

int num, result;

Must be:

int num = 0;
int result = 0;

It’s best to do what you are trying to do without any parameters ref, simply using the return value of the method:

private static int Double(int num)
{
    return num * 2;
}

And use it like this:

public static void Main()
{
    int num = readNumber("Enter an integer to be doubled: ");
    int result = Double(num);
    Console.WriteLine("The double of {0} is {1}", num, result);
    Console.WriteLine("Press enter to exit...");
    Console.ReadLine();
}

(IMO) .

+5

' signatur, double ref?

private static double Double(int num)
{
    return num * 2;
}

result = Double(num).

0

Source: https://habr.com/ru/post/1619168/


All Articles