1

How to return the variable "string" from the "switch"?

There is a method

public string ParsingAll(int i, string cssSelector, string attr) 
{
  try
  {
    string str1 = "def";
    switch (i)
    {
      case 0: 
        var items = document.QuerySelectorAll(cssSelector); 

        str1 = items[0].TextContent.Trim();

        break;
    }
        return str1;
  }
  catch (Exception ex)
  {
    string s = ex.Message;    
  }
}

I get the error
"not all branches of code return value"

How to return the variable "string" from the "switch"?

eusataf
  • 807
  • 1
  • 12
  • 24
  • 2
    The catch block doesn't return anything – Steve Dec 31 '18 at 11:55
  • 2
    Possible duplicate of [c# returning error "not all code paths return a value"](https://stackoverflow.com/questions/21197410/c-sharp-returning-error-not-all-code-paths-return-a-value) – Liam Dec 31 '18 at 11:55

3 Answers3

1

Just add a return to your catch (or after it that would cover all branches by itself):

  catch (Exception ex)
  {
    string s = ex.Message;    
  }

return null;  

}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
1

You are missing a return statement in catch block.

Generally, I would prefer a return null statement out of all try catch blocks to avoid these issues.

public string ParsingAll(int i, string cssSelector, string attr) 
{
  try
  {
    string str1 = "def";
    switch (i)
    {
      case 0: 
        var items = document.QuerySelectorAll(cssSelector); 

        str1 = items[0].TextContent.Trim();

        break;
    }
        return str1;
  }
  catch (Exception ex)
  {
    string s = ex.Message;    
    throw ;/// OR handle exception, log it, etc based on your requirements.
  }

  return null;
}
Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
1

Your catch does not return anything, but the ParsingAll method requires you to return a string.

You could return null as suggested by @uɐʞɥsɐ or throw an exception:

catch (Exception ex)
{
    string s = ex.Message;
    throw;
}
Kenci
  • 4,794
  • 15
  • 64
  • 108