3

I want to return a view if an object(country) is not null. But I get the error "Not All code paths return a value"

My code looks like this

public ActionResult Show(int id)
{
    if (id != null)
    {
        var CountryId = new SqlParameter("@CountryId", id);
        Country country = MyRepository.Get<Country>("Select * from country where CountryId=@CountryId", CountryId);
        if (country != null)
        {
            return View(country);
        }
    }

}

1 Answer 1

5

This happens when you are returning something from within the "if" statement. The compiler thinks, what if the "if" condition is false? That way you are not returning anything even when you have the return type of "ActionResult" defined in the function. So add some default returns in the else statement:

public ActionResult Show(int id)
{

    if (id != null)
    {
        var CountryId = new SqlParameter("@CountryId", id);
        Country country = MyRepository.Get<Country>("Select * from country where CountryId=@CountryId", CountryId);

        if (country != null)
        {
            return View(country);
        }
        else
        {
            return View(something);
        }
    }
    else
    {
        return View(something);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.