Serenity
Serenity

Reputation: 5098

Need help with Error: not all code paths return a value

my method's like this:-

protected string myMethod()
    {

        if (something)
        {
            string img = "A";
            return img;
        }
        else
          if(something else)
           {
              string img = "B";
              return img;
            }

    }

When I run the code "not all code paths return a value" is displayed..why so ? the method is returning that "string img" then why this error?

Upvotes: 0

Views: 158

Answers (5)

Thorin Oakenshield
Thorin Oakenshield

Reputation: 14672

protected string myMethod() 
{ 

    if (something) 
    { 
        string img = "A"; 
        return img; 
    } 
    else 
      if(something else) 
       { 
          string img = "B"; 
          return img; 
        }
reture some_String_To_Return 

} 

Upvotes: 1

Kay
Kay

Reputation: 712

Same as the other answers, but much more compact one -

protected string myMethod()
{
    return (something)? "A" : ((something else)? "B" : string.Empty);
}

Upvotes: 2

NOtherDev
NOtherDev

Reputation: 9672

If both something and something else are not true, nothing can be executed and there's no string to return. If your something is just something else's negation, you shouldn't have any condition after else.

Upvotes: 2

CD..
CD..

Reputation: 74106

the problem is if the something is false and also somthing else is false.

this should be better:

protected string myMethod()
{
    string img = string.Empty;
    if (something)
    {
        img = "A"
    }
    else 
       if(something else)
       {
          img = "B";

        }
    return img;
}

Upvotes: 4

Ed Swangren
Ed Swangren

Reputation: 124642

Ask yourself; what happens if 'something else' is false? What is returned then?

Upvotes: 6

Related Questions