0

What is this strange looking block after else in this code ???

            try
            {
                if (ossdSpreadSheet == null)
                    psErrorMessage = "Spread sheet document not created, cannot proceed!";
                else if (oXMLWriter == null)
                    psErrorMessage = "Add new sheet first before writing to sheet of workbook!";                
                {
                    oXMLWriter.WriteStartElement(new Row());
                    bValid = true;
                }
                return bValid;
            }
            catch (Exception ex)
            {
                psErrorMessage = ex.Message;
                return false;
            }

I suppose it is a static block, but what is it's use ?

shubham srivastava
  • 309
  • 1
  • 2
  • 8
  • 1
    It's a variable scope. If the code had declared variables inside it, they would've been available only inside this scope. In this case it's completely unnecessary. – Lasse V. Karlsen May 08 '19 at 10:10
  • 1
    It *may* be a leftover from previous code and the programmer made an error when editing the code, who knows, but the code will be executed regardless of the result of the if-statement (assuming no exception is thrown). – Lasse V. Karlsen May 08 '19 at 10:11
  • 2
    It's bad code altogether. When `oXMLWriter` is `null`, the code will still attempt to call `WriteStartElement()` on it, and throw a `NullReferenceException` that will then be caught. Looks indeed like an `else` was removed there. – CodeCaster May 08 '19 at 10:11
  • @LasseVågsætherKarlsen is it same like the using block then ? – shubham srivastava May 08 '19 at 10:12
  • @CodeCaster yeah Sonarcube is also showing this as a bug that's why i asked here what is this code doing. – shubham srivastava May 08 '19 at 10:13
  • No, not quite. And I think this code is just missing an `else` before that block. Time to go digging in the git history to see when/why this was changed and hopefully what it looked like before. – Lasse V. Karlsen May 08 '19 at 10:13
  • 2
    It's possible an `else` has somehow been deleted between line 6-7. – Chris Pickford May 08 '19 at 10:14
  • May be the original version doesn't check for null, and someone just introduced a check without checking the full code. I suggest you to find that person and give him a 600 page C# programming book to read. – Thangadurai May 08 '19 at 10:16
  • yeah i guess the code was missing the else keyword before that block. Thank you for the help @LasseVågsætherKarlsen – shubham srivastava May 08 '19 at 10:17

0 Answers0