ASP.NET MVC: Code Nuggets

<% %>, <%= %>, and <%: %> have special meaning:

Code enclosed within <% %> will be executed
Code enclosed within <%= %> will be executed, and the result will be outputted to the page
Code enclosed within <%: %> will be executed, and the result will be outputted to the page, as well as being HTML encoded

If you’re on ASP.NET 4 or later, you’ll want to use the <%: %> syntax vs. the <%= %> syntax, as the result gets HTML encoded.

C#: static constructors, static classes

If you want to dynamically set a static member (i.e. read it from a database or file), you can make use of a static constructor. Here are some interesting notes about static constructors:

  • The static constructor runs before any instance constructors run.
  • Static constructors don’t take an access modifier and can’t take parameters.
  • Static constructors execute only one time, no matter how many instances are created.
  • Static constructors get called when an instance of the class is created or before the first static member of the class is accessed.
  • A class or structure can define only 1 static constructor.