Search code examples
delphiif-statementdelphi-7

Where does this `else` statement end?


Trying to convert this bit of Delphi code to C# and I'm confused on where the following else part of the if/else statement actually ends. Below is the exact formatting of the code:

 try
   Root:=ExtractFileRoot(FileName);
   ErrorStr:=ExtractFileRoot(FileName)+' invalid name';
   if not GetNextNumericSegment(Root,Segment) then exit;  
   if length(Segment) = 4 then
   begin
      Year:=StrToInt(Segment);
      GetnextNumericSegment(Root,Segment)
   end
   else // Where does this else statement end?
       Year:=Defaultyear;
    ErrorStr:=ExtractFileRoot(FileName)+' invalid';
   if Length(Segment) <> 3 then exit;
   Jday:=StrToInt(Segment);
    ErrorStr:=ExtractFileRoot(FileName)+' Bad File';
   if not GetNextNumericSegment(Root,Segment) then exit;  // bad Time of day
   GetTimeFromFileName:=EncodeDate(Year,1,1)+Jday-1+
                        EncodeTime(StrToInt(Copy(Segment,1,2)),StrToInt(Copy(Segment,3,2)),StrToInt(Copy(Segment,5,2)),0);
 except
       GetTimeFromFileName:=0;
 end;

I know you don't have to use a begin/end, but everything I've seen so far in this code has used it. I also read that you don't need a ; in the if part of the statement and that the first ; after the else is the end of the else.

My guess is that everything under the else and up to the except is part of the else statement.

Note: This would be easy if I could actually debug, but unfortunately I'm just being given snippets of code and functions to convert with no real context.


Solution

  • I suggest reading the documents, If Statements.

    After else follows a statement. Each statement (structured or not) can be ended by a semicolon separator ;.

    The statement can be compound. In that case it is enclosed within a begin/end construct.

    In your case the else statements ends with Year := DefaultYear;


    I recommend to always use a ´begin/end´ pair, even if the statement is a single line. The code is more readable and if you would add a line later, less mistakes would follow.