3

I am checking logs of exception and I came across an exception in lazy loading with glass mapper. I have a sitecore project with mvc and one of the views (shared cshtml) contains the following loop:

@foreach(var item in @Model.Collection)...

I would usually write:

 @foreach(var item in Model.Collection)...

I tried googling, but I found nothing. I have inherited this code from another guy, who I cannot contact. The website actually loads the page with no error. I've tried the same loop in pure MVC and it loads the page with no Error. However, I get this lazy loading issue that the entity is null there in logs (sitecore).

I will know more tomorrow, but I am curious regarding this. Has anyone came across such issue?

Marek Musielak
  • 26,832
  • 8
  • 72
  • 80
nkalfov
  • 439
  • 5
  • 12

1 Answers1

4

I guess it works because C# allows the @ character at the beggining of a variable name (or any identifier, as @recursive pointed out in a comment). Actually this is used to allow having variable names that are also reserved words. After escaping the foreach, the code executed will look like:

foreach(var item in @Model.Collection)

And this is valid code in C#

thepirat000
  • 12,362
  • 4
  • 46
  • 72
  • I would use that in the case to escape htmlAttributes as in: `@Html.ActionLine("Details", "Details", "Home", null, new { @id = 1 })` I haven't seen in in the foreach until now, though. Well, I guess the exception is due something else. However, the stack trace end with the foreach. – nkalfov Jul 15 '15 at 23:34
  • 2
    You can use @ as a prefix to any identifier in C#, not just variables. And that's always true. There's no exception. – recursive Jul 15 '15 at 23:47
  • The bug turned out to be something from another world. I was curious about the use of @ however. Thanks for help :) – nkalfov Jul 16 '15 at 14:09