I tried to use the following code in ASP.net C#:
@{
var Host = Request.ServerVariables["HTTP_HOST"];
if (Host.Contains("example.com")) {
var Online = true;
}
if (Online == true) {
// Analytics Code
}
}
But it returned error.
I found that variable Online
cannot be used outside because its scope is limited to the IF statement in which it is declared.
Through trial and error I found that the following code works:
@{
var Host = Request.ServerVariables["HTTP_HOST"];
if (Host.Contains("example.com")) {
Page.Online = true;
}
if (Page.Online == true) {
// Analytics Code
}
}
Why is this that the second snippet works although it should not because variable scopes are expected to end at closing }
of IF statement?
Thanks
Because in the 2nd statement, it does not declare a variable, but rather only set it's value. Page.Online
was probably declared&initialized in the base class of the Page
itself.