Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# returning a list OR an int

Is it possible to return a List OR an int in a method?

Something like:

  • if it succeeded: return List
  • if it failed: return int (that gives an error number) or string with error message.

(failed as in no exceptions but the values are incorrect, like PointF.X = below 0 or Lowest value is over 10).

Now I'm doing it like this:

public List<PointF> GetContourInfoFromFile(string a_file)
{
    ListContourPoints.Clear();
    List<string> textLines = new List<string>();

    bool inEntitiesPart = false;
    bool inContourPart = false;

    try
    {
        foreach (string str in File.ReadAllLines(a_file))
        {
            textLines.Add(str);//Set complete file in array
        }

        for (int i = 0; i < textLines.Count; i++)
        {
            //read complete file and get information and set them in ListContourPoints
        }

        //Check Coordinate values
        for (int i = 0; i < ListContourPoints.Count; i++)
        {
            //Coordinates are below -1!
            if (ListContourPoints[i].X < -1 || ListContourPoints[i].Y < -1)
            {
                ListContourPoints.Clear();
                break;
            }
            //Lowest X coordinate is not below 10!
            if (mostLowestXContour(ListContourPoints) > 10)
            {
                ListContourPoints.Clear();
                break;
            }
            //Lowest Y coordinate is not below 10!
            if (mostLowestYContour(ListContourPoints) > 10)
            {
                ListContourPoints.Clear();
                break;
            }
        }
    }
    catch (Exception E)
    {
        string Error = E.Message;
        ListContourPoints.Clear();
    }
    return ListContourPoints;
}

When I do it like this, I know there is something wrong with te values.. but not specifically what.

So how can I solve this? If it's not possible with returning a list OR string/int, what's the best solution?

like image 955
Bart88 Avatar asked Oct 28 '25 16:10

Bart88


1 Answers

You can

Solution 1:

throw exception if error, and in your code above do a try catch

Delete the part catch in your function, and when you call you function do it in try catch like this:

try
{
    List<PointF> result = GetContourInfoFromFile(youfile);
}
catch (Exception E)
{
    string Error = E.Message;
}

Solution 2:

return an object with Listresult and error as property

like image 73
Esperento57 Avatar answered Oct 31 '25 05:10

Esperento57