What are dynamic properties?

5

I'm studying ASP.NET and saw the following code snippet:

ViewBag.QtdNovosComunicados =  
(from
   c in comunicados
 where
   c.DataCadastro > UsuarioLogado.dtUltimoAcesso
 select
c).Count();

I understand that I am creating a new property in class ViewBag .

But how will it define this dynamic property? .NET does this at runtime? Can type problems occur when I access this property later?

    
asked by anonymous 20.10.2017 / 17:02

1 answer

6

ViewBag is an object, not a class. It is a property of View that is used to mount the page.

Values are passed to the View at runtime, but this does not mean that they are poorly typed. If you try to use these values in a way that types do not allow, you will have exceptions. For example, the result of a call to Count() as in the example in question is integer - if you try to call a method that does not have integer, such as Dispose() , you get an error.

Just one more thing: ViewBag is a very easy thing to use to commit abuses, and so its use is considered at best a code smell (euphemism for small gambiarra) , and at worst an anti-standard. The traditional way of passing data to View is to fill that data in Model , not ViewBag .

    
20.10.2017 / 17:13