-1

I have declared a method in a class to compare two numbers and I'm having an issue. I'm getting an error saying not all code paths return a value. I want to return an int for every matching number in the char arrays. Here is an image of the code.

public int CompareCodes(string rndselect, string personselect)
{
    char[] rndnumber = rndselect.ToCharArray(); //take the randoms elected one and convert it to a char array
    char[] perNum = personselect.ToCharArray();
    likeness0 = 0;
    likeness1 = 1;

    foreach (char RndNum in rndnumber)
    {
        foreach (char Pnum in perNum)
        {
            if (RndNum == Pnum)
            {
                return likeness1;
            }
            else
            {
                return likeness0;
            }
        }
    }
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
James
  • 3
  • 2
  • 2
    Possible duplicate of [C# error: not all code paths return a value](http://stackoverflow.com/questions/19903404/c-sharp-error-not-all-code-paths-return-a-value) – Eugene Podskal Mar 06 '16 at 11:13
  • Hi James. Before you post your question you will be presented some questions that are similar to yours. Simple problems like this usually already have been asked and answered. – Krisztián Balla Mar 06 '16 at 11:15
  • your `int CompareCodes` method must have returned value because maybe your foreach not run for never! – Behzad Mar 06 '16 at 11:15

3 Answers3

4

What should compiler think if your perNum is empty?

NikitaKo
  • 300
  • 2
  • 12
3

The error says exactly what is wrong with your code. Having a foreach loop doesn't guarantee anything inside the foreach is executed. If rndnumber or perNum happens to be empty, there is nothing to loop through and your code actually doesn't return anything.

Dirk Trilsbeek
  • 5,873
  • 2
  • 25
  • 23
0

If rndselect or perNum is empty string. So no value is returned.

If you sure these string are always not null. so add

return 0

at the end of block.

Tuan Le
  • 53
  • 8