开发者

Why is this C# code kicking up an error?

real newbie question but why doesn't this work? I am getting

use of unassigned variable 'comparison'

as the error

        string comparison;
        Console.WriteLine("Enter the first number");
        int firstNum = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the second number");
        开发者_JAVA百科int secondNum = Convert.ToInt32(Console.ReadLine());
        if (firstNum == secondNum)
            comparison = "equals to";
        if (firstNum < secondNum)
            comparison = "less than";
        if (firstNum > secondNum)
            comparison = "greater than";
        Console.WriteLine("{0}",comparison);


Because the compiler doesn't know comparison was in an executable path. Change the three ifs to if-then-elses:

    if (firstNum == secondNum)
        comparison = "equals to";
    else if (firstNum < secondNum)
        comparison = "less than";
    else
        comparison = "greater than";

and it will work


It's almost self explanatory - comparison cannot be guaranteed to be assigned (have a value) and the compiler throws an error as a result of this.

Basically your if statements may never set a value to 'comparison' and this is why it's failing.

A quick and dirty way round this would be to declare comparison in a manner similar to this

string comparison = "unassigned";

or

string comparison = String.Empty;


The other answers here are correct. The issue is that C# requires all variables to be definitely assigned before they are used.


You can set comparison to string.Empty as well when you declare it ...


The basic issue here is that the compiler will not check a series of conditionals like this to see that in combination they cover all possible options. Anything in the conditional is considered may-be-executed and that's that, it never looks at the big picture.

As Jesse said, make it a single if else if else so the compiler can see there are no other paths. It's slightly more efficient anyway as your code always executes all three tests whereas his executes at most two tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜