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?