Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Online is a variable:

var Online = true;

Page is an object. It's actually a built-in object that belongs to the web request context you're operating in. It's also a dynamic object, which means it doesn't have a fixed type. Its type is inferred at runtime.

Page.Online

Page.Online isn't a variable as such. It's a dynamic property belonging to Page. One feature of dynamic objects is that you can assign anything to them, and all any method, and the compiler won't complain. It defers resolution until runtime, where its value is inferred from the context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top