Why does ViewBag.SomeProperty not throw an exception if the property does not exist?

In MVCsometimes, I set a specific property ViewBagaccording to some condition. For example:

if(someCondition)
{
   // do some work
   ViewBag.SomeProperty = values;
}

return View();

In mine, ViewI check if the property is null:

@if(ViewBag.SomeProperty != null)
{
   ...
}

So far, I thought I should throw an exception, because if my condition is not met, then it SomePropertywill never be set. And so I always used the instruction elseto set this property to null. But I just noticed that it does not make an exception, even if the property does not exist. For example, in Console Application, if I do the following, I get RuntimeBinderException:

dynamic dynamicVariable = new {Name = "Foo"};

if(dynamicVariable.Surname != null) Console.WriteLine(dynamicVariable.Surname);

But that does not happen when it comes to ViewBag. Who cares?

+4
2

AFAIK ViewBag - ViewData. ViewData :

public object this[string key]
{
    get
    {
        object value;
        _innerDictionary.TryGetValue(key, out value);
        return value;
    }
    set { _innerDictionary[key] = value; }
}

, , .

+7

ViewBag DynamicViewDataDictionary, null .

+1

Source: https://habr.com/ru/post/1534568/


All Articles