3
    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).

pnuts
  • 58,317
  • 11
  • 87
  • 139
Dave Jellison
  • 924
  • 13
  • 22
  • 1
    The reason is clear, ViewBag is dynamic. I don't have an answer but looking for CC+Dynamic will give more results than CC+MVC – H H Jul 05 '11 at 09:24
  • Good thought. Will refine my googling and certainly post if I find a solution. For now, I had to turn off Null checking on the DBC property page. It would be nice if Code Contracts allowed us to ignore dynamic type altogether. – Dave Jellison Jul 08 '11 at 10:54
  • Actually - now I remember this comment "Thanks, yup, we need to do some work to recognize this pattern or implicitly have some contracts about these helper fields/methods." SO isn't letting me post the link but you can certainly google that statement...darn. Thanks Henk, the answer is...there is no answer yet but will leave this open should a CC update provide a solution. – Dave Jellison Jul 08 '11 at 10:58

1 Answers1

1

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.

Manuel Fahndrich
  • 665
  • 4
  • 12