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();
    }
}
4
  • You want out int result in the method signature. But most of the time I'd do it without using refand out alltogether .... Commented Dec 9, 2015 at 8:56
  • yep, it says that the variable result in the Main method is unassigned. Yeah but I want to practice ref Commented Dec 9, 2015 at 8:56
  • 1
    Use out instead of ref. Even better, don't use them at all if you don't have to. Commented Dec 9, 2015 at 8:57
  • 1
    Possible Duplicate - Why compile error “Use of unassigned local variable”? Commented Dec 9, 2015 at 8:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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).

1 Comment

And remove the parameter result, it's now unnecessary/confusing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.