Archive for May, 2016

Razor and the @ symbol

Wednesday, May 18th, 2016

Another programmer asked me about when you use the @ symbol in Razor. This was my reply…

The @ sign is used for switching in and out of code. It is a razor thing – a bit like for most things. It can be used in the following ways (might be others I have missed too): –

To set the ModelType at the top
You can add in a block of code with
@Code

End Code
When you are in HTML, to call a function that outputs HTML or text
It usually works out where the end of the function call is by itself and switches back to HTML
If it doesn’t get it right, you can put brackets in – eg. @(Now.ToString(“dd/MM/yyyy”))
You can also use it to include an If/Using/With/loop in HTML – eg.

@For Each o in Orders
@

Next

When you are in code, to switch back to HTML, by placing it before an HTML tag
eg.
For Each o in Orders
@

Next
If you don’t want to output an HTML tag, you can use @ to switch back
When you are in code, you can use it to write the output of a function into the HTML – eg.

For Each o in Orders
@o.CustomerName @
Next

It is worth noting that you can call these functions from within code – eg. Html.LabelFor, but if you don’t stick the @ on the beginning, they won’t get written to the HTML – the result won’t go anywhere!

Also worth pointing out that you can nest back and forwards between HTML and code – eg..

@Code
If Model.Data.Count>0 Then
@

@For Each o in Model.Data
@


Next

Order ID Customer Name
@o.ID @o.Customer.Name

Else
@No results
End If
End Code

Lambda functions/subs in VB.NET

Wednesday, May 18th, 2016

Another programmer was asking me why you sometimes need “End Sub” on a Lambda Sub and sometimes you don’t. This was my reply…

There are 2 types of Lambda methods – inline and multi line. Inline is all on one line, so you can do…

Sub (x) DoSomethingWith(x)

nb. this is the same as

Sub (x) _
DoSomethingWith(x)

because VB.NET considers that multiple lines with _ at the end are all one. However, without the _ it is multiline…

Sub (x)
DoSomethingWith(x)
YouCanAlsoDoSomethingElseWith(x)
End Sub

That’s when you need End Sub – even if it is only one line in the body, you need to end it if you aren’t doing the body on the same line as the declaration.

nb. Functions work the same way, although there is one other difference with functions. Multiline functions work the same way as usual in terms of how you return from them, but inline you don’t use the Return keyword, so you would just do eg.

Function (x) x*2

In all of the above examples, you would want to provide types on the parameters (eg. x As Decimal). For inline functions, you can usually let the compiler work out the return type, but for multiline you should usually explicitly declare the return type (eg. Function(x As Decimal) As Decimal)