4

I'm learning C# by myself by book and would appreciate some help. I want to create a simple console program to allow the user to enter a number to be doubled. It says that the variable result in the Main method is unassigned, 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();
    }
}
  • You want `out int result` in the method signature. But most of the time I'd do it without using `ref`and `out` alltogether .... – EluciusFTW Dec 09 '15 at 08:56
  • yep, it says that the variable result in the Main method is unassigned. Yeah but I want to practice `ref` –  Dec 09 '15 at 08:56
  • 1
    Use `out` instead of `ref`. Even better, don't use them at all if you don't have to. – Umut Seven Dec 09 '15 at 08:57
  • 1
    [Possible Duplicate - Why compile error “Use of unassigned local variable”?](http://stackoverflow.com/q/9233000/1324033) – Sayse Dec 09 '15 at 08:59

2 Answers2

5

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

Meaning:

int num, result;

Should be:

int num = 0;
int result = 0;

There may be a better way of doing what you're trying to do, without any ref parameters at all, by simply using the return value of the method:

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

And consume 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();
}

This may even (IMO) enhance the readability of your code and convey your intentions better.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

´Why don´t you simply change the methods signatur to return a double instead of using a ref?

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

Now you can simply call result = Double(num).

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111