asp.net-mvc-3razorcode-contractsmicrosoft-contracts

Code Contracts with new MVC 3 ViewBag


    public class HomeController : Controller
{
    public ActionResult Index()
    {
        // Warning  19  CodeContracts: Possibly calling a method on a null reference 'Website.Controllers.HomeController.<Index>o__SiteContainer0.<>p__Site2.Target'    HomeController.cs

        if (ViewBag != null)
        {
            ViewBag.Message = "Be Immortal";
        }

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

Wracking my brain trying to figure out how to satisfy [X] Implicit Non-Null Obligations for the ViewBag in MVC 3. Has anyone come up with a way to make code contracts jive with the new dynamic ViewBag type?

I'd preferably like to be able to wrap the ViewBag in a base controller as ViewBagSafe etc.

I do realize this is not really a problem with the project since ViewBag will never be null but I would like to leave code-contracts on with default null-checking for future slip-ups on my part (and still be able to compile without warnings so that I can easily identify my own contract-breaking coding).


Solution

  • I tracked down the problem. It has to do with the initialization logic of dynamic member lookups and the static caching fields emitted by the C# compiler. I had to teach cccheck about these and add some contracts to the caching classes in System.Core.dll. The next release should no longer issue these warnings on dynamically access members. Thanks for bringing it up.