1

I have to output an employee's name and dept in the view like Welcome 'employee' to 'dept'. I am using string.Format(). I was playing around with String.Format and string.Format() and saw the following. Can someone please explain why string.Format() doesn't work or what am i missing in the code? I was reading online and saw that string.Format() and String.Format() give the same result.

Doesn't work-

<div>
  <div> Welcome </div>
    <div>
       @if(employee != null)
       {
           @string.Format("{0} at {1}", employee.name, emp.dept)
       }
    </div>
</div>

Error- Unexpected "string" keyword after "@" character. Once inside code, you do not need to prefix constructs like "string" with "@".

Works:

<div>
  <div> Welcome </div>
   <div>
     @if(employee != null)
     {
        @(string.Format("{0} to {1}", employee.name, emp.dept))
     }
   </div>
</div>

Works

<div>
   <div> Welcome </div>
     <div>
        @if(employee != null)
        {
            @String.Format("{0} at {1}", employee.name, emp.dept)
        }
   </div>
</div>
user3478233
  • 67
  • 1
  • 7
  • The message is self explanatory. Just remove the `@` Your already inside a code block so its just `string.Format(...)` –  Sep 01 '15 at 00:13
  • This is a known bug. See here: http://stackoverflow.com/questions/15543841/possible-breaking-change-in-mvc4-razor-that-can-be-fixed-with – Rob Sep 01 '15 at 00:14
  • 1
    As for the reason - Razor recognizes `string` as a keyword, but not `String` – Rob Sep 01 '15 at 00:15
  • @Steve - closed to be duplicate of two posts "what `@` means in C#" and "@string.Format not working in Razor". Not that "Possible breaking change in MVC4 Razor..." is possibly better duplicate, but `@string` / `@String` in context to C# as shown in the post refer to *variable* with name `string`/`String` correspondingly - thus causing very strange behavior. – Alexei Levenkov Sep 01 '15 at 00:24
  • @StephenMuecke - I would not say the message is self-explanatory - correct error (and indeed self explanatory at that) would be "The name 'string' does not exist in the current context" (regular C# error for such code), this is mix of C#/Razor syntax and has several strange cases like that. – Alexei Levenkov Sep 01 '15 at 00:30

0 Answers0