Understanding C# compilation error with ternary operator

前端 未结 2 1662
礼貌的吻别
礼貌的吻别 2020-12-19 19:04

I have copied the following code from Wrox Professional ASP.NET 4.0 MVC 4 book, page 179 (Chapter \"Understanding the Security Vectors in a Web Application\") w

相关标签:
2条回答
  • 2020-12-19 19:39

    The compiler expects the same return type in a conditional statement, so it expects both of these to be the same type. If you cast the options to ActionResult, it will work. You may be able to get along with the compiler by only casting the last one.

    return (Url.IsLocalUrl(returnUrl)) ? (ActionResult)Redirect(returnUrl) : (ActionResult)RedirectToAction("Index", "Home");
    
    0 讨论(0)
  • 2020-12-19 19:48

    It doesn't compile because the compiler decides what the return-type of the one-liner is based upon one of the two return-values. Since type B doesn't derive of type C, or the other way around, the two types are not mutually exclusive, and the return type of the if (as a whole) cannot be derived that way.

    If you would want to do it in a one-liner, you have to cast the return-values to the type that you want to return, which is type A.

    private A Function(){
        return (condition) ? ((A)new B()): ((A)new C());
    }
    

    UPDATE: I didn't see that you already do the casting in your question, my apologies.

    0 讨论(0)
提交回复
热议问题