-3

is there something missing here?

private int existb1b2(Bill b1, ArtQty artQty)
        {
            int test;
            for(int i = 0; i < b1.ArtQty.Count(); i++)
            {
                if (b1.ArtQty[i].Article.Name == artQty.Article.Name)
                    test = 0;
                else
                    test = -1;
            }
            return test;
        }

I got Error: Use of unassigned local variable 'test'

I think that test should be initialized.

el-chico
  • 145
  • 1
  • 11

1 Answers1

2

You have a couple problems - first, you need to assign an initialize value to test, because there is no guarantee you will even enter the for loop. This is the source of your error.

Second, you probably want to return 0 if you have a match - the way the code is written, it will actually return -1 even if a match is found unless the LAST item in your list is the match. You are probably better off to simply return the moment a match is found, no need to iterate the rest of the items, and no local variable assignment is even required.

Try this:

private int existb1b2(Bill b1, ArtQty artQty)
{
    for (int i = 0; i < b1.ArtQty.Count(); i++)
    {
        if (b1.ArtQty[i].Article.Name == artQty.Article.Name) return 0;
    }
    return -1;
}

Or if you just want to fix your compilation error, you could change your int test; line to int test = -1;

Steven Hansen
  • 3,189
  • 2
  • 16
  • 12
  • Additional possible improvement: in most languages, 1 is true and 0 is false. This code uses a very unusual representation of these two values by subtracting each by 1. However, in C# you would ideally use `bool` rather than int. – Magus Oct 09 '14 at 22:49
  • Agreed, bool would be better. – Steven Hansen Oct 09 '14 at 22:51
  • How if I would like to return the position? It shows the same error when I make `return i`! – el-chico Oct 09 '14 at 23:10
  • Make a new question and show your code. To return the position of the found item, wouldn't you just use `return i`? – Steven Hansen Oct 09 '14 at 23:11