Just came across an interesting effect while debugging a View. The scenario is easy to reproduce - I have a breakpoint in a View
, in the Watch window I add ViewBag.ViewData
and the value is null
. However, if I just add ViewBag
and expand the object, I can see the ViewData
and it is not null
. I can also successfully expand it and see its properties.
Can anyone explain whether it's a bug or what causes this behavior?
EDIT
ViewBag.ViewData
is actually null
. E.g. if I have this code in the View:
if (ViewBag.ViewData == null)
{
<span>ViewBag.ViewData is null</span>
}
it displays the span. So the weird part is that I can expand it in the watch window and see the properties.
EDIT2
In response to @Darin Dimitrov's answer - I tried to reproduce this behavior with a custom test class and I get a RuntimeBinderException
when trying to access the private property: 'SomeClass.SomeProperty' is inaccessible due to its protection level
:
public class SomeClass
{
private string SomeProperty;
}
dynamic dynamicObject = new SomeClass();
if (dynamicObject.SomeProperty == null)
{
Console.WriteLine("dynamicObject.SomeProperty is null");
}
In this case, shouldn't I be getting the same exception when accessing ViewBag.ViewData
in the View (the line with if (ViewBag.ViewData == null)
)?
RuntimeBinderException
instead ofnull
when I try to accessViewBag.ViewData
(see EDIT2 to my question)? And btw, I appreciate you reminding about the evilness of ViewBag and ViewData, but that's not necessary - I am a strong proponent of strongly typed viewmodels myself ;) – Country