tomu tomu - 3 months ago 9
C# Question

Variables in for loop can not be returned?

I know this is very basic, but I really cannot see where is the problem in this code

private int Linesel(List<GraphicsPath> LineGroup)
{
int selectedline;
for (int i =0; i < LineGroup.Count; i++)
{
Pen pen = new Pen(Color.Navy, 8);
if (LineGroup[i].IsOutlineVisible(Latest, pen))
{
selectedline = i;

}
else if (!LineGroup[i].IsOutlineVisible(Latest, pen))
{
selectedline = -1;

}

}
return selectedline;
}


The return variable is informed as a error by the complier.
What mistake have I made

Answer

The problem you are facing is, when your for loop has no iterations (LineGroup.Count == 0), selectedline has no value. The compiler You could solve it with:

int selectedline = default(int);

Like Scott said, 0 is also a valid value. You could solve it two ways.

  • returning a not valid but detectable value.

    private int Linesel(List<GraphicsPath> LineGroup)
    {
        for (int i =0; i < LineGroup.Count; i++)
        {
            Pen pen = new Pen(Color.Navy, 8);
            if (LineGroup[i].IsOutlineVisible(Latest, pen))
            {
                return i;
            }
        }
    
        return -1;
    }
    

    OR

    private int? Linesel(List<GraphicsPath> LineGroup)
    {
        for (int i =0; i < LineGroup.Count; i++)
        {
            Pen pen = new Pen(Color.Navy, 8);
            if (LineGroup[i].IsOutlineVisible(Latest, pen))
            {
                return i;
            }
        }
    
        return null;
    }
    

    use it like:

    var res = Linesel(....);
    if(!res.HasValue)
    {
        // problem
    }
    else
    {
        // ->   res.Value;
    }
    

  • Raising an exception

    private int Linesel(List<GraphicsPath> LineGroup)
    {
        for (int i =0; i < LineGroup.Count; i++)
        {
            Pen pen = new Pen(Color.Navy, 8);
            if (LineGroup[i].IsOutlineVisible(Latest, pen))
            {
                return i;
            }
        }
    
        throw new Exception("WHATEVER"); // <-- you might create your own 
    }
    
Comments