Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ViewBag.SomeProperty doesn't throw an exception when the property is not exists?

In MVC, sometimes I'm setting specific property of ViewBag according to some condition.For example:

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

return View();

In my View I'm checking whether the property is null like this:

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

Until now I was thinking that should throw an exception because if my condition is not satisfied then SomeProperty is never get set.And that's why I was always using an else statement to set that property to null.But I just noticed, it doesn't throw an exception even if the property doesn't exists.For example in a Console Application if I do the following, I'm getting a RuntimeBinderException:

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

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

But it doesn't happen when it comes to ViewBag.What's the difference ?

like image 653
Selman Genç Avatar asked Apr 02 '14 01:04

Selman Genç


2 Answers

AFAIK the ViewBag is a dynamic wrapper around ViewData. And ViewData itself retrieves the values as follows:

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

hence, if key doesn't exist it returns default value for type and doesn't throw exception.

like image 191
Petr Abdulin Avatar answered Sep 18 '22 09:09

Petr Abdulin


ViewBag inherits from DynamicViewDataDictionary which returns null for missing properties.

like image 20
SlightlyMoist Avatar answered Sep 17 '22 09:09

SlightlyMoist