Computer Magic Logo
Parenthesis

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

There are cases that Razor engine needs more information in order to know exactly what we expect to be generated. Parenthesis help us to inform the Razor engine about where the code starts and where it ends. This is very useful when we use operators in our code. Let’s see an example.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    int a = 3;
    int b = 5;    
}
<p>@a + b</p>

In the example above we declared two variables and we expect that the Razor engine will add the two values and the result will appear on the screen. The problem is that if we execute this code the output will be the following:

<p>3 + b</p>

This happens because Razor engine finds that after the @ character we have placed a variable and it supposes that after the variable we have HTML code to display and it will never make the calculation. In order to solve this problem we can wrap the calculation in a pair of parenthesis.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    int a = 3;
    int b = 5;
}
<p>@(a + b)</p>

Now we inform the Razor engine that what we want to place at this position is the calculation and the final output will be the following.

<p>8</p>

The parenthesis is not useful only for calculations. Another example is that sometimes the Razor engine thinks that instead of placing a variable after tha @ character it is the domain name of an email. Let’s see an example.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    string HelloWorld = "Hello World!";
}
<p>Value@HelloWorld</p>

In this example we declare a variable called HelloWorld and we try to display its contents by using the @ character. If we try to execute this example we will see that the output will be the following.

<p>Value@HelloWorld</p>

This happens because Razor engine things that this is an email address and it will not display the contents of the HelloWorld variable. In order to fix it we can use the parenthesis characters like the following example in order to correct this problem.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    string HelloWorld = "Hello World!";
}
<p>Value@(HelloWorld)</p>

Now the output will be the following:

<p>ValueHello World!</p>